· problem solving · 3 min read
Resolve enumeration operation may not execute

Problem statement
We have a collection of data the hold all employees data. Employees are working in Tech and other is not configured in same database table. for one scenario, I should filter the employees whos not blong to both dept , we should ignore them for bonus. How to filter only those?
Code
Note : written by other colleague,
Employee class and datas:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int Age { get; set; }
public string Address { get; set; } = string.Empty;
}
public class Employees
{
public List<Employee> GetEmployees()
{
return AllEmployees;
}
private List<Employee> AllEmployees { get; set; } =
[
new Employee { Id = 1, Name = "John Doe", Age = 30, Address = "123 Main St" },
new Employee { Id = 2, Name = "Jane Smith", Age = 25, Address = "456 Elm St" },
new Employee { Id = 3, Name = "Robert Brown", Age = 40, Address = "789 Oak St" },
new Employee { Id = 4, Name = "Emily Davis", Age = 32, Address = "101 Pine St" },
new Employee { Id = 5, Name = "Michael Johnson", Age = 28, Address = "202 Maple Ave" },
new Employee { Id = 6, Name = "Sophia Wilson", Age = 35, Address = "303 Birch Blvd" },
new Employee { Id = 7, Name = "Daniel Garcia", Age = 29, Address = "404 Cedar Lane" },
new Employee { Id = 8, Name = "Olivia Martinez", Age = 27, Address = "505 Spruce Rd" },
];
}
public class TechEmployee
{
public List<int> Ids { get; set; } = [1,4,6];
}
public class OtherEmployee
{
public List<int> Ids { get; set; } = [2,3,7,8];
}
Solution(Has Problem):
Employees employee=new Employees();
TechEmployee techEmployee=new TechEmployee();
OtherEmployee otherEmployee=new OtherEmployee();
var employees = employee.GetEmployees();
foreach (var emp in employees)
{
var isTechEmployee = techEmployee.Ids.Find(x=>x==emp.Id);
var isOtherEmployee = otherEmployee.Ids.Find(x=>x==emp.Id);
if (isTechEmployee == 0 && isOtherEmployee == 0)
employees.Remove(emp);
}
Problem statement
In above code while we fetch employees list one by one and checking data is present in other list. and if its not available in both both we have remove from the same list. So it will show the exception
Error Message: System.InvalidaOperationException: Collection was modified; enumeration operation may not execute
Solution (fix):
With the help of linq , filter and remove operation to be done in single query. otherwise, need a temporary variable hold all result and again we have to set the same to employees object/list.
employees.RemoveAll(emp =>
{
var isTechEmployee = techEmployee.Ids.Find(x => x == emp.Id);
var isOtherEmployee = otherEmployee.Ids.Find(x => x == emp.Id);
return isTechEmployee == 0 && isOtherEmployee == 0;
}
);