简体   繁体   中英

C#: How can I sort rows in 2D array in ascending order based on highest value in one column?

So I've got a table of data in 2D array (first column is an ordinal number of the rows and the rest are data I'm working with). My question is basically how can I sort the rows based on the highest value in the last column (ie if the fourth row got the highest value in the last column it moves up to first row, and so on). random in the code is just a method I made for generating floating numbers between x and y.

My code so far looks like this:

static float random(float min, float max)
        {
            System.Random random = new System.Random();
            double val = (random.NextDouble() * (max - min) + min);
            return (float)val;
        }
static void Main(string[] args)
        {

            int temp = 0, i, j;
            float[,] matrix;
            matrix = new float[10, 5];
            
            //generating ordinal number
            for (i = 0; i < 10; i++)
            {
                matrix[i, 0] = ++temp;
            }
            //generating rest of the 2D array
            for (i = 0; i < 10; i++)
            {
                for (j = 0; j < 5; j++)
                {
                    matrix[i, 1] = random(60, 100);
                    matrix[i, 2] = random(50, 100);
                    matrix[i, 3] = random(40, 100);
                    matrix[i, 4] = (matrix[i, 1] + matrix[i, 2] + matrix[i, 3]) / 3;
                }
            }
            
            for (i = 0; i < 10; i++)
            {
                for (j = 0; j < 5; j++)
                {
                    Console.Write(matrix[i, j] + "\t");
                }
                Console.WriteLine();
            }
            Console.WriteLine();

        }

I suggest using jagged array (array of array) float[][] instead of 2d one float[,] . With jagged array you can sort in one simple line:

    using System.Linq;

    ...

    float[][] matrix = ...

    // Column to compare
    int column = 4; // or matrix[0].Length - 1; for the last olumn

    Array.Sort(matrix, (left, right) => left[column].CompareTo(right[column]))); 

If you insist on having float[,] you can copy it into jagged array, sort and then copy back:

    float[,] matrix = ...

    int column = 4;

    float[][] temp = Enumerable
      .Range(0, matrix.GetLength(0))
      .Select(i => Enumerable
         .Range(0, matrix.GetLength(1))
         .Select(j => matrix[i, j])
         .ToArray())
      .ToArray(); 

    Array.Sort(temp, (left, right) => left[column].CompareTo(right[column])); 

    for (int i = 0; i < temp.Length; ++i)
      for (int j = 0; j < temp[i].Length; ++j)
        matrix[i, j] = temp[i][j];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM