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?
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; });
list.RemoveAll(bk => bk.Level != 5);
list.RemoveAll(delegate(Book b) { return b.Level == 5; });
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
精彩评论