从列表中删除多个值

3

我定义了一个列表如下:

List<List<int>> thirdLevelIntersection = new List<List<int>>();

我写的代码是

for(int i = 0; i < 57; i++)
{
    if(my condition)
        thirdLevelIntersection[i] = null;
    else
    {
       //some logic
    }    
}

我得到了0到56个值的列表,一些任意值是null,如thirdlevelIntersection [1]、thirdlevelIntersection [10]、thirdlevelIntersection [21]、thirdlevelIntersection [21]、thirdlevelIntersection [14]、thirdlevelIntersection [15]、thirdlevelIntersection [51](总共7个)。

现在我想从列表中删除这些值。

并且获得从thirdlevelIntersection [0]到thirdlevelIntersection [49]的列表。

我该怎么做?

3个回答

3

当你完成循环后,请尝试

thirdLevelIntersection.RemoveAll(list => list == null);

不用谢。但从技术上讲,这不是 Linq。RemoveAll 是 List<T> 的实例方法,而 Linq(-to-objects)是在 IEnumerable<T> 上实现的扩展方法。 - Anthony Pegram

1
如果你要从某种类型的sourceCollection创建thirdLevelIntersection,你可以使用Linq。
List<List<int>> thirdLevelIntersection = 
    (from item in sourceCollection
     where !(my condition)
     select item)
    .ToList();

或者,如果您正在通过多个语句构建列表,则可以在创建列表时进行。
thirdLevelIntersection.AddRange(
    from item in sourceCollection
    where !(my condition)
    select item);

这样做可以避免添加后再从列表中删除项目的必要性。

它能够工作,但对于像我这样的新手来说,理解Linq太困难了。你能告诉我一个合适的来源吗?让我对Linq有个概念。感谢你的回答。 - user2213564
@user2213564 学习Linq的最佳地方是这里 - p.s.w.g

0

在遍历列表时,您可以通过调用RemoveAt()然后递减i(这样下一个值就会被考虑)来实现此操作。

List<List<int>> thirdLevelIntersection = new List<List<int>>();

for(int i=0;i<57;i++)
{
    if (my condition)
    {
        thirdLevelIntersection.RemoveAt(i--);
        continue;
    }
    else
    {
        //some logic
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接