在我的应用程序,_collection是一个列表,从中我需要删除所有用户对象不匹配的标准
但是,下面的code得到一个无效的操作在其第二次迭代错误,因为_collection本身已经改变了:
的foreach(在_collection用户的用户)
{
如果(!user.IsApproved())
{
_collection.Remove(用户);
}
}
我可以创建另一个列表的收集和复制他们来回,但后来才知道有非克隆的引用类型的问题,等等。
有没有办法做到上面更优雅比复制_collection到另一另一个列表变量?
解决方案 _collection.RemoveAll(用户=>!user.IsApproved());
如果你的还是的在2.0:
_collection.RemoveAll(委托(用户U){返回u.IsApproved();});
顺便说一句,如果你不想要触摸原始列表,你可以得到的另一个的批准用户提供清单:
_collection.FindAll(用户=> user.IsApproved());
In my application, _collection is a List from which I need to remove all User objects which do not match the criteria.
However, the following code gets an invalid operation error in its second iteration since the _collection itself has been changed:
foreach (User user in _collection)
{
if (!user.IsApproved())
{
_collection.Remove(user);
}
}
I could create another List collection and copy them back and forth but then I have the issue of non-cloned reference types, etc.
Is there a way to do the above more elegantly than copying _collection to another another List variable?
解决方案_collection.RemoveAll(user => !user.IsApproved());
If you're still on 2.0:
_collection.RemoveAll(delegate(User u) { return !u.IsApproved(); });
By the way, if you don't want to touch the original list, you can get another list of approved users with:
_collection.FindAll(user => user.IsApproved());