Hesam E
Hesam E

Reputation: 107

How to keep some columns and rows of jagged array and remove unwanted columns and rows in c#

I have following jagged array

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

and I learned how to delete one specific column and row (for example 3). Here's a link.

Now I want to have dynamic programming as follows: consider this array

     int[] day={1,4,5};

this array can be another array (I used dynamic term for this reason)

where the elements of array "day" shows the "dists1" matrix rows and columns, so I want the new jagged array named as " dists2" contains only columns and rows of 1,4,5 with row and column "0" because it is fixed row and column as follow:

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

Upvotes: 2

Views: 475

Answers (1)

Mehrzad Chehraz
Mehrzad Chehraz

Reputation: 5147

Simply modify that answer and replace the i != 2 condition with Contains method of the day array:

int[] day = {1,4,5};
int[][] finalDists = 
        dists.Where((arr, i) => i == 0 || day.Contains(i)) //skip rows
       .Select(arr=> arr.Where((item, i) => i == 0 || day.Contains(i)) //skip cols
       .ToArray())
       .ToArray();

Anyway if performance matters, it is way better to use for loops instead of LINQ.

Upvotes: 2

Related Questions