Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific objects from a list

Tags:

c#

I have a class that has an list<Book> in it, and those Book objects has many many properties. How can I remove from that list every Book that his level value is different than, for example, 5?

like image 217
iTayb Avatar asked Mar 22 '10 15:03

iTayb


People also ask

How do you remove certain items from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do I remove an object from a list of objects?

There are two ways to remove objects from ArrayList in Java, first, by using the remove() method, and second by using Iterator. ArrayList provides overloaded remove() method, one accepts the index of the object to be removed i.e. remove(int index), and the other accept objects to be removed, i.e. remove(Object obj).

How do I remove a specific value from a list index?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output.


1 Answers

In this particular case, List<T>.RemoveAll is probably your friend:

C# 3:

list.RemoveAll(x => x.level != 5);

C# 2:

list.RemoveAll(delegate(Book x) { return x.level != 5; });
like image 125
Jon Skeet Avatar answered Oct 14 '22 02:10

Jon Skeet