Removing items from an anchor list

In one of my projects, I am trying to remove an item from the list where the identifier is equal to this identifier.

I have a BindingList<T> named UserList .

The lists have all the RemoveAll() methods.

Since I have a BindingList<T> , I use it like this:

 UserList.ToList().RemoveAll(x => x.id == ID ) 

However, my list contains the same number of items as before.
Why is this not working?

+7
source share
3 answers

This does not work because you are working with a copy of the list that you created by calling ToList() .

BindingList<T> does not support RemoveAll() : it is only a List function, therefore:

 var itemToRemove = UserList.Where(x => x.id == ID).ToList(); foreach (var item in itemToRemove) UserList.Remove(item); 

We call ToList() here, because otherwise we will list the collection when it changes.

+14
source

You may try:

 UserList = UserList.Where(x => x.id == ID).ToList(); 

If you use RemoveAll() inside a generic class that you are going to use to store a collection of objects of any type, like this:

 public class SomeClass<T> { internal List<T> InternalList; public SomeClass() { InternalList = new List<T>(); } public void RemoveAll(T theValue) { // this will work InternalList.RemoveAll(x =< x.Equals(theValue)); // the usual form of Lambda Predicate //for RemoveAll will not compile // error: Cannot apply operator '==' to operands of Type 'T' and 'T' // InternalList.RemoveAll(x =&amp;gt; x == theValue); } } 

This content is taken from here .

+2
source

If there is only one item inside the link list as a unique identifier, the simple code below may work.

 UserList.Remove(UserList.Where(x=>x.id==ID).First()); 
0
source

Source: https://habr.com/ru/post/907951/


All Articles