Sort a Multidimensional array by column c#

Question:

I have a multidimensional array:

string[,] classificacao = new string[20, 2];

and which has the following inputs:

classificação[0,0]="Hamilton"; //ISTO É O NOME DO JOGADOR

classificação[0,1]="20"; //ISTO A SUA PONTUAÇÃO

classificação[1,0] = "Vettel";

classificação[1,1]="34";

Between others

How can I sort in descending order by score column without losing the player's name?

That is:

Vettel - 34

Hamilton - 20

Answer:

The .NET Framework does not have functions for ordering multidimensional arrays directly – the ordering functions mainly work for jagged arrays. One solution is for you to convert your array to jagged , order it, and then convert it back. The code below shows an example of this:

class PtStackOverflow_209128
{
    public static void Test()
    {
        string[,] classificacao = new string[4, 2];
        classificacao[0, 0] = "Hamilton"; //ISTO É O NOME DO JOGADOR
        classificacao[0, 1] = "104"; //ISTO A SUA PONTUAÇÃO
        classificacao[1, 0] = "Vettel";
        classificacao[1, 1] = "129";
        classificacao[2, 0] = "Bottas";
        classificacao[2, 1] = "75";
        classificacao[3, 0] = "Räikkönen";
        classificacao[3, 1] = "67";

        var jagged = ToJagged(classificacao);
        Array.Sort(jagged, (i1, i2) => int.Parse(i2[1]) - int.Parse(i1[1]));
        classificacao = ToRectangular(jagged);
        for (int i = 0; i < classificacao.GetLength(0); i++)
        {
            for (int j = 0; j < classificacao.GetLength(1); j++)
            {
                Console.Write("{0} ", classificacao[i, j]);
            }

            Console.WriteLine();
        }
    }

    static T[][] ToJagged<T>(T[,] array)
    {
        int height = array.GetLength(0), width = array.GetLength(1);
        T[][] jagged = new T[height][];

        for (int i = 0; i < height; i++)
        {
            T[] row = new T[width];
            for (int j = 0; j < width; j++)
            {
                row[j] = array[i, j];
            }
            jagged[i] = row;
        }
        return jagged;
    }
    static T[,] ToRectangular<T>(T[][] array)
    {
        int height = array.Length, width = array[0].Length;
        T[,] rect = new T[height, width];
        for (int i = 0; i < height; i++)
        {
            T[] row = array[i];
            for (int j = 0; j < width; j++)
            {
                rect[i, j] = row[j];
            }
        }
        return rect;
    }
}

(The conversion functions were copied from this SOen answer ).

Scroll to Top