通过List 删除不需要的对象的最简单方法是什么?
在我的应用程序中,_collection是一个List,我需要从中删除所有与条件不匹配的User对象 。
但是,以下代码在其第二次迭代中获取无效操作错误,因为_collection本身已更改:
foreach (User user in _collection) { if (!user.IsApproved()) { _collection.Remove(user); } }
我可以创建另一个List集合并来回复制它们,但后来我遇到了非克隆引用类型等问题。
有没有办法比将_collection复制到另一个另一个List变量更优雅?
_collection.RemoveAll(user => !user.IsApproved());
如果你还在 2.0:
_collection.RemoveAll(delegate(User u) { return !u.IsApproved(); });
顺便说一句,如果您不想触摸原始列表,您可以获得另一个已批准用户列表:
_collection.FindAll(user => user.IsApproved());
您始终可以从顶部索引开始并向下迭代到0:
for (int i = _collection.Count - 1; i >= 0; i--) { User user = _collection[i]; if (!user.IsApproved()) { _collection.RemoveAt(i); } }
不过,Mehrdad的回答看起来非常优雅。
只要有可能在循环中修改集合,请选择for
循环。 Mehrdad给出的解决方案很可爱,绝对值得一试!
这是我在处理可修改集合时发现有用的代码:
for(int index=0;index < _collection.Count; index++) { if (!_collection[index].IsApproved) { _collection.RemoveAt(index); index--; } }