gpt4 book ai didi

c# - 修改 Foreach 循环中的集合 C#

转载 作者:行者123 更新时间:2023-12-03 01:45:03 25 4
gpt4 key购买 nike

我在 foreach 循环期间更新 ObservableCollection 中的项目时遇到问题。基本上,我有一个员工 ObservableCollection ,他们的模型中有一个字段可以决定他们是否在建筑物中。

我不断地查看数据库表来检查每个员工,看看这个状态是否有任何变化。这就是我在 C# 中执行此操作的方法;

public ObservableCollection<EmployeeModel> EmployeesInBuilding {get; set; }
public ObservableCollection<EmployeeModel> Employees {get; set; }

var _employeeDataService = new EmployeeDataService();
EmployeesInBuilding = _employeeDataService.GetEmployeesInBuilding();
foreach (EmployeeModel empBuild in EmployeesInBuilding)
{
foreach (EmployeeModel emp in Employees)
{
if (empBuild.ID == emp.ID)
{
if (empBuild.InBuilding != emp.InBuilding)
{
emp.InBuilding = empBuild.InBuilding;
int j = Employees.IndexOf(emp);
Employees[j] = emp;
employeesDataGrid.Items.Refresh();
}
}
}
}

这正确地识别了两个 ObseravbleCollections 之间的更改,但是当我去更新现有的 ObservableCollection 时,我得到一个异常:Collection was generated;枚举操作可能无法执行。

如何防止这种情况发生并仍然修改原始集合?

最佳答案

当您只需设置元素的属性时,无需替换 Employees 集合中的元素。

相反,您的 EmployeeModel 类应该实现 INotifyPropertyChanged 接口(interface),并在 InBuilding 属性更改时引发 PropertyChanged 事件:

public class EmployeeModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

private bool inBuilding;
public bool InBuilding
{
get { return inBuilding; }
set
{
if (inBuilding != value)
{
inBuilding = value;
OnPropertyChanged("InBuilding");
}
}
}

private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

...
}

现在更新代码的内部循环可以简化为:

foreach (var emp in Employees)
{
if (empBuild.ID == emp.ID)
{
emp.InBuilding = empBuild.InBuilding;
}
}

或者你像这样编写整个更新循环:

foreach (var empBuild in EmployeesInBuilding)
{
var emp = Employees.FirstOrDefault(e => e.ID == empBuild.ID);

if (emp != null)
{
emp.InBuilding = empBuild.InBuilding;
}
}

关于c# - 修改 Foreach 循环中的集合 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36351523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com