使用比较列表对列表进行排序

时间:2013-02-27 12:01:50

标签: c# list sorting

需要在c#中做这样的事情我在java中做的事情:

Double[][] matrix = new Double[3][4];

        matrix[0][0] = 100.0;
        matrix[0][1] = -3.0;
        matrix[0][2] = 50.0;
        matrix[0][3] = 50.3;

        matrix[1][0] = 1.2;
        matrix[1][1] = 1.1;
        matrix[1][2] = 0.9;
        matrix[1][3] = 10000.0;

        matrix[2][0] = 2.3;
        matrix[2][1] = 2.35;
        matrix[2][2] = 2.32;
        matrix[2][3] = 2.299;

        Arrays.sort(matrix, new Lexical());

我一直在查看MSDN文档,除了排序List之外没有任何方法,对List<List<T>>没有任何内容。

感谢

3 个答案:

答案 0 :(得分:2)

豪尔赫。

一种可能的解决方案:

matrix.Sort(delegate(List<double> l1, List<double> l2)
            {
               return l1[0].CompareTo(l2[0]);
            });

再见。

答案 1 :(得分:0)

您可以实现自己的IComparer和排序,或者您可以使用Linq执行某些操作,它基本上将遍历整个矩阵并对其进行排序,或者您可以将其转换为另一个数据结构,类似于List&gt;然后你可以轻松地对它进行排序。

或类似的东西:

How do I sort a two-dimensional array in C#?

http://www.codeproject.com/Tips/166236/Sorting-a-two-dimensional-array-in-C

答案 2 :(得分:0)

您可以按每个数组的第一个元素排序(如果这就是您所要求的):

var matrix = new double[][] {
    new[] { 100.0, -3.0, 50.0, 50.3 },
    new[] { 1.2, 1.1, 0.9, 10000.0 },
    new[] { 2.3, 2.35, 2.32, 2.299}
};

Array.Sort(matrix, (a, b) => a[0].CompareTo(b[0]));