[英]Deleting multiple values from the list
I have defined one list as 我已将一个列表定义为
List<List<int>> thirdLevelIntersection = new List<List<int>>();
I wrote the code as 我把代码编写为
for(int i = 0; i < 57; i++)
{
if(my condition)
thirdLevelIntersection[i] = null;
else
{
//some logic
}
}
so i get the list for 0 to 56 values and some arbitrary values are null like thirdlevelIntersection[1],thirdlevelIntersection[10],thirdlevelIntersection[21],thirdlevelIntersection[21],thirdlevelIntersection[14],thirdlevelIntersection[15],thirdlevelIntersection[51](total 7). 所以我得到0到56个值的列表,一些任意值为null,如thirdlevelIntersection [1],thirdlevelIntersection [10],thirdlevelIntersection [21],thirdlevelIntersection [21],thirdlevelIntersection [14],thirdlevelIntersection [15],thirdlevelIntersection [51] ](共7)。
Now i want to remove this values from the list. 现在我想从列表中删除这些值。
And have a list from thirdlevelIntersection[0] thirdlevelIntersection[49]. 并且有一个来自thirdlevelIntersection [0] thirdlevelIntersection [49]的列表。
What should I do? 我该怎么办?
完成循环后,请尝试
thirdLevelIntersection.RemoveAll(list => list == null);
If you're creating thirdLevelIntersection
from a sourceCollection
of some type you can use Linq. 如果您从某种类型的sourceCollection
创建thirdLevelIntersection
,则可以使用Linq。
List<List<int>> thirdLevelIntersection =
(from item in sourceCollection
where !(my condition)
select item)
.ToList();
Or if you're building up the list over multiple statements you can do it as you are creating it: 或者,如果您在多个语句中构建列表,则可以在创建时执行此操作:
thirdLevelIntersection.AddRange(
from item in sourceCollection
where !(my condition)
select item);
This eliminates the necessity to remove items from a list once they've been added. 这样就无需在添加项目后从列表中删除项目。
You can do this while you're iterating over the list by calling RemoveAt()
and then decrementing i
(so the next value is considered). 您可以通过调用RemoveAt()
然后递减i
(因此考虑下一个值RemoveAt()
来迭代列表时执行此操作。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.