从锯齿数组中删除多维数组的行

3

我有一个包含多维数组的不规则数组,并且想要移除其中的一个数组。我的代码如下:

int[][,] arr = new int[4][,];

arr[0] = new int[,] { 
  { 1, 2, 3 }, // <- I want to remove this row 
  { 4, 5, 6 }, 
  { 5, 6, 7 }, 
  { 8, 9, 10 } };

arr[1] = new int[,] { 
  { 1, 2, 3, 4 }, 
  { 5, 6, 7, 8 }, 
  { 9, 10, 11, 12 }, 
  { 13, 14, 15, 16 } };

arr[2] = new int[,] { 
  { 1, 2, 3, 4, 5 }, 
  { 5, 6, 7, 8, 9 }, 
  { 10, 11, 12, 13, 14 },
  { 15, 16, 17, 18, 19 } };

arr[3] = new int[,] { 
  { 1, 2, 3, 4, 5, 6}, 
  { 5, 6, 7, 8, 9, 10}, 
  { 11, 12, 13, 14, 15, 16 }, 
  { 17, 18, 19, 20, 21, 22 } };
      
int[,] removeArray = { { 1, 2, 3 } };

我尝试使用Linqarr[0]中删除{1, 2, 3}

arr = arr
  .Where((val, i) => i != 0)
  .ToArray();

但是这会移除整个arr[0]。有人知道如何使用Linq来移除{1,2,3}吗?


你想要清空移除列表中的所有元素,但不清空包含它们的数组? - T. Nielsen
与“锯齿形”数组不同,多维数组没有任何内部数组,这就是为什么您无法删除它们的原因;您所能做的就是重新创建2D数组。 - Dmitry Bychenko
是的。基本上我只想从a [0]中删除一个数组{1,2,3}。 - Valkyrie
@Valkyrie,您是否也想删除 {1, 2, 3} 在其他位置出现的任何内容,还是只有当它完全相同才删除? - T. Nielsen
你的问题与C#语言版本5.0有关,具体是什么? - Rand Random
1个回答

3

jagged 数组不同,多维 数组不包含数组:

int[][] jagged = new int[][] {
  new[] { 1, 2, 3 }, // <- this is an array
  new[] { 4, 5 },    // <- this is another array
};

int[,] array2D = new int[,] {
  { 1, 2, 3 },       // <- not an array
  { 4, 5, 6 },       // <- not an array 
};

如果你想从2D数组中删除某一行,你需要重新创建一个新的数组,例如:

private static T[,] RemoveRows<T>(T[,] source, T[] row) {
  if (row.Length != source.GetLength(1))
    return source;

  var keepRows = new List<int>(); 

  for (int r = 0; r < source.GetLength(0); ++r) 
    for (int c = 0; c < row.Length; ++c)
      if (!object.Equals(source[r, c], row[c])) {
        keepRows.Add(r);

        break;
      }

  if (keepRows.Count == source.Length)
    return source;

  T[,] result = new T[keepRows.Count, source.GetLength(1)];

  for (int r = 0; r < keepRows.Count; ++r)
    for (int c = 0; c < result.GetLength(1); ++c)
      result[r, c] = source[keepRows[r], c];

  return result;
}

接着

// we remove row; let it be 1d array, not 2d one
int[] removeArray = { 1, 2, 3 };

arr = arr
  .Select(array => RemoveRows(array, removeArray))
  .ToArray();

请使用.NET Fiddle进行尝试


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接