通过List <T>删除不需要的对象的最简单方法是什么?

Edw*_*uay 8 .net c# generics collections list

在我的应用程序中,_collection是一个List,我需要从中删除所有条件不匹配的User对象.

但是,以下代码在第二次迭代中获取无效操作错误,因为_collection本身已更改:

foreach (User user in _collection)
{
    if (!user.IsApproved())
    {
        _collection.Remove(user);
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以创建另一个List集合并来回复制它们,但后来我遇到了非克隆引用类型等问题.

有没有办法比将_collection复制到另一个另一个List变量更优雅?

Meh*_*ari 54

_collection.RemoveAll(user => !user.IsApproved());
Run Code Online (Sandbox Code Playgroud)

如果你还在 2.0:

_collection.RemoveAll(delegate(User u) { return !u.IsApproved(); });
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果您不想触摸原始列表,您可以获得另一个已批准用户列表:

_collection.FindAll(user => user.IsApproved());
Run Code Online (Sandbox Code Playgroud)