簡體   English   中英

C#:如何根據一列中的最大值按升序對二維數組中的行進行排序?

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

所以我有一個二維數組中的數據表(第一列是行的序數,rest 是我正在使用的數據)。 我的問題基本上是如何根據最后一列中的最高值對行進行排序(即,如果第四行在最后一列中獲得最高值,它會向上移動到第一行,依此類推)。 代碼中的random數只是我在 x 和 y 之間生成浮點數的一種方法。

到目前為止,我的代碼如下所示:

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();

        }

我建議使用鋸齒狀數組(數組數組) float[][]而不是2d one float[,] 使用鋸齒狀數組,您可以在一個簡單的行中進行排序:

    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]))); 

如果您堅持使用float[,]您可以將其復制到鋸齒狀數組中,排序然后復制回來:

    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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM