I am having an issue with updating an item in an ObservableCollection
during a foreach
loop. Basically I have an ObservableCollection
of employees, and they have a field in their model that decides whether or not they are in a building.
I am constantly looking at a database table to check every employee to see if there is any change in this status. This is how I do this in 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();
}
}
}
}
This correctly picks up a change between the two ObseravbleCollections
, however when I go to update the existing ObservableCollection
I get an exception: Collection was modified; enumeration operation may not execute.
How can I prevent this from happening and still modify the original collection?