Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete one column and row from jagged array in c#

Tags:

c#

I have following jagged array of "dists"

int[][] dists = new int[][]
{
    new int[]{0,2,3,5,2},
    new int[]{2,0,1,3,5},
    new int[]{3,1,0,4,4},
    new int[]{5,3,4,0,2},
    new int[]{2,5,4,2,0}
};

now I want to create another jagged array named as finalDists when I remove the 3rd row and 3rd column from original array of dists. I mean I want finally have following jagged array:

int[][] finalDists = new int[][]
{
    new int[]{0,2,5,2},
    new int[]{2,0,3,5},
    new int[]{5,3,0,2},
    new int[]{2,5,2,0}
}; 

I am confused how to handle this issue, before all thanks for your help

like image 777
Hesam E Avatar asked Apr 19 '15 10:04

Hesam E


2 Answers

int[][] finalDists = dists.Where((arr, i)=>i!=2) //skip row#3
                          .Select(arr=>arr.Where((item,i)=>i!=2) //skip col#3
                                          .ToArray())
                          .ToArray();
like image 55
ASh Avatar answered Sep 21 '22 11:09

ASh


Not very optimized but:

public static T[] RemoveRow<T>(T[] array, int row)
{
    T[] array2 = new T[array.Length - 1];

    Array.Copy(array, 0, array2, 0, row);
    Array.Copy(array, row + 1, array2, row, array2.Length - row);

    return array2;
}

public static T[][] RemoveColumn<T>(T[][] array, int column)
{
    T[][] array2 = new T[array.Length][];

    for (int i = 0; i < array.Length; i++)
    {
        array2[i] = RemoveRow(array[i], column);
    }

    return array2;
}

and

int[][] dists = new int[][]
{
    new int[]{0,2,3,5,2},
    new int[]{2,0,1,3,5},
    new int[]{3,1,0,4,4},
    new int[]{5,3,4,0,2},
    new int[]{2,5,4,2,0}
};

int[][] dists2 = RemoveColumn(RemoveRow(dists, 2), 2);

Note that you want to remove the third row and the third column, but their index is 2, because .NET arrays are 0-based indexed!

like image 44
xanatos Avatar answered Sep 18 '22 11:09

xanatos