There's a button click event in a lengthy code I've written. I have a list of objects in it. Each time the button is clicked, the list should be modified ( for example, some items should be removed ) and then iterated using a foreach loop.
List<Person> lp=new List<Person>();
lp.RemoveAt(2);
foreach(Person j in lp)
{
// do something
}
When I try to execute the above code, it results in an exception.
InvalidOperationException : Collection was modified; enumeration operation may not execute.
I found some solutions on the internet and tried them. One of them is,
foreach(Person j in lp.ToList())
{
// do something
}
But nothing could stop the exception.
can someone help with this ?