如何从C#中的数组null中删除​​所有object[,]元素。我已经在StackOverflow中看到了类似的问题:Remove blank values in the array using c#

问题是他们使用名为Where()的方法来解决简单数组类型object[]的问题,但是我正在处理数组类型object[,],不幸的是,此类没有实现方法Where() 。例如 :

object[,] data = new object[2,2]{{null,null},{1,2}};


然后,data包含:

[0, 0] [object]:null
[0, 1] [object]:null
[1, 0] [object]:1
[1, 1] [object]:2


如您所见(在我的特定情况下),如果一个元素为null,则此元素的所有行均为null。我想得到:

[0, 0] [object]:1
[0, 1] [object]:2


有什么帮助吗?

最佳答案

方法如下:


计算您要删除的行数
创建适当大小的数组
复制您要保留的行


使用辅助方法来检测带有null的行:

static bool RowHasNull(object[,] data, int row) {
    return Enumerable.Range(0, data.GetLength(1)).Any(c => data[row,c] == null);
}


现在实现看起来像这样:

var oldRowCount = data.GetLength(0);
var newRowCount = oldRowCount - Enumerable.Range(0, oldRowCount).Count(r => RowHasNull(data, r));
if (newRowCount == 0) ... // the array is empty, do something about it - e.g. throw an exception
var res = new object[newRowCount, data.GetLength(1)];
int r = 0;
for (var row = 0 ; row != oldRowCount ; row++) {
    if (RowHasNull(data, row)) {
        continue;
    }
    for (int c = 0 ; c != data.GetLength(1) ; c++) {
        res[r,c] = data[row, c];
    }
    r++;
}
return res;

10-06 05:25
查看更多