如何删除 2D 列表中的空列表
本文关键字:列表 2D 何删除 删除 | 更新日期: 2023-09-27 18:00:14
我有一个 2D 列表,但尚未填写 2D 列表中的每个列表。因此,2D 列表包含一些列表,但这些列表并未全部填写。如果没有填写,我想删除它们。我该怎么做?这是我到目前为止得到的:
List<List<string>> list = new List<List<string>>();
for (int i = 0; i < list.count;i++)
{
if (list[i][0] == "") //Or has it to be == NULL?
{
list[i].Remove(); //.Remove tells me it takes 0 arguments
}
}
在你的代码中,行
if (list[i][0] == "") //Or has it to be == NULL?
假定索引 i
处的子列表至少有一个元素。
list[i].Remove(); //.Remove tells me it takes 0 arguments
要删除特定索引处的项目,您必须使用 RemoveAt
:
list.RemoveAt[i]
当你想使用Remove
时,你必须传递要删除的对象:
list.Remove(list[i])
但请注意,在for
循环中使用它时,不应更改list
,因为list.Count
是在循环开始时评估的,当您删除项目时,会遇到越界错误。
我并不完全清楚您何时真正要删除子列表,而是从list
中删除所有子列表
-
null
(l == null
( - 空 (
!l.Any()
( - 或仅包含空字符串 (
l.All(string.IsNullOrEmpty)
(
只需像这样使用 RemoveAll
方法:
list.RemoveAll(l => l == null || !l.Any() || l.All(string.IsNullOrEmpty));
而不是
list[i].Remove(); //.Remove tells me it takes 0 arguments
用
list.RemoveAt(I);
试试这个:
for (int i = 0; i < list.count;i++)
{
list[i].RemoveAll(string.IsNullOrWhiteSpace);
}