【问题标题】:How to delete empty lists in a 2Dlist如何删除二维列表中的空列表
【发布时间】:2015-06-29 11:27:53
【问题描述】:

我有一个 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
  } 
}

【问题讨论】:

  • List是哪种类型的?
  • 字符串,List>
  • 我假设您尝试了不同的方法并检查它是否真的删除了空列表。你能提出一些论据为什么你使用的方法没有成功吗?

标签: c# list for-loop


【解决方案1】:

在您的代码中,行

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));

【讨论】:

    【解决方案2】:

    代替

    list[i].Remove();  //.Remove tells me it takes 0 arguments
    

    使用

    list.RemoveAt(I);
    

    【讨论】:

      【解决方案3】:

      试试这个:

      for (int i = 0; i < list.count;i++) 
      { 
        list[i].RemoveAll(string.IsNullOrWhiteSpace); 
      }
      

      【讨论】:

      • 我认为这个问题是真正解释这段代码的基础。这很自我解释。
      猜你喜欢
      • 2021-07-25
      • 1970-01-01
      • 2016-07-13
      • 2015-09-20
      • 2021-07-11
      • 2022-06-22
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多