有没有一个简短的漂亮的方法来删除 VB.Net 中的空列表的空列表?

Is there a short an beautiful way to delete empty Lists of an empty List in VB.Net?

我得到了一个整数列表。虽然一些嵌套列表包含整数,但有些不包含。

Dim innerList1 As New List(Of Integer)
Dim innerList2 As New List(Of Integer)
Dim innerList3 As New List(Of Integer)
Dim outerList As New List(Of List(Of Integer))

innerList1.add(1)
innerList1.add(2)
innerList3.add(25)

outerList.add(innerList1)
outerList.add(innerList2)
outerList.add(innerList3)

输出可能如下所示:

外部列表:

innerList1: 1 2

innerList2:

innerList3:25

现在我想用下面的代码删除空的 innerList:

For i = 0 to outerList.Count() - 1
    If (outerList(i).Count() = 0) Then
        outerList.remove(outerList(i))
    End If
Next

问题是,一旦 innerList 被删除,索引将在一些迭代后超出范围。

我还尝试了 while 语句和 do 循环。但是没有任何效果。

如果有人能帮助我,我将不胜感激:)

好的,我找到了遮阳篷。 我只是以相反的方向循环我的列表,所以索引永远不会超出范围。

简短而漂亮的方法是使用 RemoveAll 方法,它将删除所有满足特定条件的项目:

outerList.RemoveAll(Function(l) l.Count = 0)

请注意,这也是使用 ListCount 属性,而不是 Enumerable.Count 扩展方法。通过像您一样添加括号,您正在调用该扩展方法。当您知道列表是什么类型并且它有专用的 属性 时,请不要这样做,例如Count 此处或 Length 数组。

或使用 LINQ:

outerList = outerList.Where(Function(x) x.Count > 0).ToList()

(注意,这用一个新的替换了 outerList。如果你在一个 sub/function 中,其中 outerList 已通过 ByVal(并且这不是使用 ByRef 的建议)那么调用子赢了'看到变化)