In one of my projects I'm trying to remove an item from a list where the id is equal to the given id.
I have a BindingList<T>
called UserList
.
Lists have all the method RemoveAll()
.
Since I have a BindingList<T>
, I use it like that:
UserList.ToList().RemoveAll(x => x.id == ID )
However, my list contains the same number of items as before.
Why it's not working?
It's not working because you are working on a copy of the list which you created by calling ToList()
.
BindingList<T>
doesn't support RemoveAll()
: it's a List<T>
feature only, so:
IReadOnlyList<User> usersToRemove = UserList.Where(x => (x.id == ID)).
ToList();
foreach (User user in usersToRemove)
{
UserList.Remove(user);
}
We're calling ToList()
here because otherwise we'll enumerate a collection while modifying it.