[英]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. 我有一个类中有一个
list<Book>
,而这些Book
对象有很多属性。 How can I remove from that list every Book that his level
value is different than, for example, 5? 如何从每个Book中删除他的
level
值不同于例如5?
In this particular case, List<T>.RemoveAll
is probably your friend: 在这种特殊情况下,
List<T>.RemoveAll
可能是你的朋友:
C# 3: C#3:
list.RemoveAll(x => x.level != 5);
C# 2: 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. 虽然List.RemoveAll()是一个很好的解决方案,但它会对集合产生“foreach”,从而导致O(n)或更差的性能。 If you have lots of items in the list, i would suggest checking out Erick's Index 4 Objects collections.
如果列表中有很多项目,我建议查看Erick的Index 4 Objects集合。
See http://www.codeplex.com/i4o 见http://www.codeplex.com/i4o
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.