1

Please how do I sort the following array (in C#) by the second column desc, then by the first column asc (and then insert the resulting rank in the third column which I guess might be a separate question). I'm a beginner in C#, I have spent quite some time looking for an answer to this seemingly simple question, but I couldn't find any approach that would work for me. Any help is much appreciated, thanks.

int[,] myArray = new int[5, 4]
{
   {1, 7, 0, 0} ,
   {2, 12, 0, 0} ,
   {3, 15, 0, 0} ,
   {4, 7, 0, 0} ,
   {5, 1, 0, 0}
};

1 Answer 1

4

In a multidimensional array, there isn’t really a concept of “rows”. All values are just in the same relation to another. That’s why sorting multidimensional arrays is somewhat tricky.

It gets easier when you use jagged arrays, basically arrays of arrays. Your array would look like this:

int[][] myJaggedArray = new int[][]
{
   new int[] { 1, 7, 0, 0 },
   new int[] { 2, 12, 0, 0 },
   new int[] { 3, 15, 0, 0 },
   new int[] { 4, 7, 0, 0 },
   new int[] { 5, 1, 0, 0 },
};

You can also convert your multidimensional array into a jagged array, doing something like this:

int[][] myJaggedArray = new int[myArray.GetUpperBound(0) + 1][];
for(int i = 0; i < myJaggedArray.Length; i++)
    myJaggedArray[i] = Enumerable.Range(0, myArray.GetUpperBound(1) + 1).Select(k => myArray[i,k]).ToArray();

Once you have a jagged array, sorting it is really easy using LINQ:

var result = myJaggedArray
    .OrderBy(row => row[1])
    .ThenBy(row => row[0])
    .Select((row, idx) =>
    {
        row[2] = idx;
        return row;
    })
    .ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

works perfectly (I just replaced the OrderBy with OrderByDescending), thanks a lot for the solution and for the explanation - I obviously misunderstood the concept of rectangular arrays

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.