Removing elements from binding list
Asked Answered
P

3

11

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?

Pallet answered 8/2, 2012 at 14:56 Comment(0)
S
19

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.

Sattler answered 8/2, 2012 at 15:0 Comment(0)
V
2

You could try:

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

If you use RemoveAll() inside a generic class that you intend to be used to hold a collection of any type object, 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.

Vasti answered 8/2, 2012 at 15:1 Comment(0)
A
0

If there is just one item as unique ID inside bindinglist, the below simple code can work.

UserList.Remove(UserList.First(x=>x.id==ID));
Aleen answered 13/12, 2018 at 18:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.