从多维数组中删除Nothing值

如何删除具有“Nothing”的值并将数组减少为具有值的数组?

假设我有一个名为modvaluestmp(,)的二维数组我使用以下linq语句来删除任何内容.它工作,但结果数组(结果)是一个单维数组.有人可以帮我返回保留索引的2D数组吗?

Dim result() = (From str In modvaluestmp
              Where Not {Nothing}.Contains(str)).ToArray()

现有的数组是这样的

modvaluestmp(0,0) = "sometext1"
modvaluestmp(0,1) = "sometext2"
modvaluestmp(0,2) = "sometext3"
modvaluestmp(0,3) = "sometext4"
modvaluestmp(0,4) = Nothing
modvaluestmp(0,5) = Nothing
modvaluestmp(1,0) = "sometext5"
modvaluestmp(1,1) = "sometext6"
modvaluestmp(1,2) = "sometext7"
modvaluestmp(1,3) = "sometext8"
modvaluestmp(1,4) = Nothing
modvaluestmp(1,5) = Nothing

我希望数组如下

modvaluestmp(0,0) = "sometext1"
modvaluestmp(0,1) = "sometext2"
modvaluestmp(0,2) = "sometext3"
modvaluestmp(0,3) = "sometext4"
modvaluestmp(1,0) = "sometext5"
modvaluestmp(1,1) = "sometext6"
modvaluestmp(1,2) = "sometext7"
modvaluestmp(1,3) = "sometext8"

最佳答案 您应该使用
jagged-array而不是方形2D阵列.所以你的代码应该是这样的:

 Dim modvaluestmp = New String(1)() {}

 modvaluestmp(0) = New String(5) {}
 modvaluestmp(1) = New String(5) {}

 modvaluestmp(0)(0) = "sometext1"
 modvaluestmp(0)(1) = "sometext2"
 modvaluestmp(0)(2) = "sometext3"
 modvaluestmp(0)(3) = "sometext4"
 modvaluestmp(0)(4) = Nothing
 modvaluestmp(0)(5) = Nothing
 modvaluestmp(1)(0) = "sometext5"
 modvaluestmp(1)(1) = "sometext6"
 modvaluestmp(1)(2) = "sometext7"
 modvaluestmp(1)(3) = "sometext8"
 modvaluestmp(1)(4) = Nothing
 modvaluestmp(1)(5) = Nothing

 Dim result = (From ary In modvaluestmp Select ary.Where(Function(str) Not str Is Nothing).ToArray()).ToArray()

帮助链接:

jagged arrays in Wikipedia

jagged arrays in MSDN

点赞