Home > Software design >  Remove row from multidimensional array in jagged array
Remove row from multidimensional array in jagged array

Time:07-23

I have a jagged array with a multidimensional array and want to remove an array inside the multidimensional array. My code is:

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

I tried to remove {1, 2, 3} from arr[0] by using Linq:

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

but this removes the whole arr[0] row. Does anyone know how I can get to remove {1,2,3} using Linq?

CodePudding user response:

Unlike jagged arrays, multidimensional ones doesn't consist of arrays:

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

So if you want to "remove" row from 2d array, you have to recreate it; something like this:

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

and then

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

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

please, fiddle yourself

  • Related