繁体   English   中英

通过列表进行预告的最简单方法是什么 <T> 删除多余的对象?

[英]What is the easiest way to foreach through a List<T> removing unwanted objects?

在我的应用程序中,_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--;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM