How can I sort a 2d array using Linq?

后端 未结 3 1204
再見小時候
再見小時候 2021-01-21 21:47

I have a 2d array of strings

string [] [] myArray;

and I want to sort it by one of the columns.

So the data might be

{          


        
相关标签:
3条回答
  • 2021-01-21 22:19

    you can do like this...

    IEnumerable<T> AsEnumerable(this T[,] arr) {
      for(int i = 0; i < arr.GetLength(0); i++)
        for(int j = 0; j < arr.GetLength(1); j++)
          yield return arr[i, j];
    }
    

    And then write for example:

    int[,] data = // get data somwhere
    // After 'AsEnumerable' you can use all standard LINQ operations
    var res = data.AsEnumerable().OrderBy(n => n).Reverse();
    
    0 讨论(0)
  • 2021-01-21 22:20
    var myOrderedRows = myArray.OrderBy(row => row[columnIndex]);
    
    0 讨论(0)
  • 2021-01-21 22:24
    Array.Sort(myArray, (p, q) => p[0].CompareTo(q[0]));
    

    This will order the array in place (so at the end myArray will be sorted). LINQ OrderBy by comparison creates a new ordered enumerable that then you can convert to a ToArray.

    0 讨论(0)
提交回复
热议问题