I’m trying to remove an item from a Generic List which is bound to a repeater control.
So far I’ve got a remove method (after scouring the interwebs) that should of been working:
Label lblMemberName = (Label)e.Item.FindControl("lblMemberName");
switch (e.CommandName)
{
case "RemoveMember":
foreach (challenge.Member member in Members.Where(member => member.Name == lblMemberName.Text))
{
//This line doesnt work
Members.Remove(member);
}
break;
}
Unfortunately, the actual removal apart of this scenario is not working.
I understand that you can’t create a new instance of a List<> to delete. So, that’s why I used the Linq statement to find the previous details.
What am I doing wrong and how could possibly ix it?
As above, you cannot modify the contents of a collection whilst iterating over it.
You could also try List(T).RemoveAll(). Refer to LINQ: How to Use RemoveAll without using For loop with Array. This is a more succinct solution than another list.