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

标签 c# wpf foreach observablecollection

我在 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/

相关文章:

c# - KeyBinding 用作 UserControl,但在 XAML 中使用属性元素语法时不起作用

wpf - 为什么 Silverlight/WP7 上的 NavigationService 在类上使用字符串?

c# - ItemsControl中子元素的加权分布

php - MYSQL 和 PHP 循环并从联合表中只抓取一个项目?

c# - 将对象从 javascript 发送到 View

c# - 帮我让这段代码工作

c# - 为什么 UInt16 数组的加法速度似乎比 int 数组快?

c# - 水平滚动条在 DataGridView 上不可见

javascript - NodeJs,javascript : . forEach 似乎是异步的?需要同步

php - 使用 foreach 和嵌套数组在带有 PHP 的 MySql 中插入行