How to sort jagged arrays by string in C #?

I have a 2D gear array. And I want to sort it by line.

I searched and found code to sort by columns

private static void Sort<T>(T[][] data, int col) { Comparer<T> comparer = Comparer<T>.Default; Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col])); } 

Can I adapt it to sort by any line?

Any help is appreciated.

Sample of my gear array (added)

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { int n = 10; int[][] capm = new int[3][]; for (int i = 0; i <= 2; i++) { capm[i] = new int[n + 1]; } Random rand = new Random(); for (int i = 1; i <= n; i++) { capm[1][i] = i; } for (int i = 1; i <= n; i++) { capm[2][i] = rand.Next(1, 6); } Sort(capm, 2); Console.ReadLine(); } private static void Sort<T>(T[][] data, int col) { data = data.OrderBy(i => i[col]).ToArray(); } } } 

@Dani and @Martin I want my cog array to sort capm [2] [].

+7
source share
2 answers

The only way I can do this is to sort by an array of indices:

 private static void Sort<T>(T[][] data, int row) { int[] Indices = new int[data[0].Length]; for(int i = 0; i < Indices.Length; i++) Indices[i] = i; Comparer<T> comparer = Comparer<T>.Default; Array.Sort(Indices, (x, y) => comparer.Compare(data[row][x], data[row][y]); for(int i = 0; i < data.Length; i++) { T[] OldRow = (T[])data[i].Clone(); for(int j = 0; j < OldRow.Length; j++) data[i][j] = OldRow[i][Indices[j]]; } } 
+4
source

Given that you are using a gear array, this sorts it by 3rd point. But a 2D array is probably better if you want to ensure that each row has the same number of columns ... If you have an array inside an array that does not have a third column, this will not work!

 private static void Sort<T>(T[][] data, int col) { data = data.OrderBy(i => i[col]).ToArray(); } 

Edit:

To do something with a new data link, you need to either return it or pass a parameter by reference:

 private static void Sort<T>(ref T[][] data, int col) { data = data.OrderBy(i => i[col]).ToArray(); } 

The array itself is not sorted; a new sorted array is created

+1
source

All Articles