iTayb
iTayb

Reputation: 12743

Remove specific objects from a list

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?

Upvotes: 9

Views: 18313

Answers (4)

unclepaul84
unclepaul84

Reputation: 1404

Although List.RemoveAll() is an excellent solution, it does a "foreach" on the collection resuling in O(n) or worse performance. If you have lots of items in the list, i would suggest checking out Erick's Index 4 Objects collections.

See http://www.codeplex.com/i4o

Upvotes: 1

Seb
Seb

Reputation: 2715

list.RemoveAll(delegate(Book b) { return b.Level == 5; });

Upvotes: 1

JoshBerke
JoshBerke

Reputation: 67068

list.RemoveAll(bk => bk.Level != 5);

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1499860

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; });

Upvotes: 28

Related Questions