C#按多列排序多维数组

时间:2015-04-21 09:31:22

标签: c# sorting multidimensional-array

我有一个多维数组,其中包含以下值:

multiarray = new int[,] {    { 8, 63  },
                             { 4, 2   }, 
                             { 0, -55 }, 
                             { 8, 57  }, 
                             { 2, -120}, 
                             { 8, 53  }  };

我需要做的是按第一列对数组进行排序,然后在第二列对值相等的位置进行排序。

理想情况下,输出应如下所示:

8, 63
8, 57
8, 53
4, 2
2, -120
0, -55

这样做的最佳方式是什么?

3 个答案:

答案 0 :(得分:1)

使用列表<> Linq的对象

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication19
{
    class Program
    {
        static void Main(string[] args)
        {
            List<List<int>> multiarray = new List<List<int>>{    
                new List<int> { 8, 63  },
                new List<int>  { 4, 2   }, 
                new List<int>  { 0, -55 }, 
                new List<int>  { 8, 57  }, 
                new List<int>  { 2, -120}, 
                new List<int>  { 8, 53  }  
            };
           

            List<List<int>> sortedList = multiarray.OrderBy(x => x[1]).OrderBy(y => y[0]).ToList();

        }
    }
}

答案 1 :(得分:1)

using System.IO;
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // declare and initialize a JAGGED array
         int[][] a=new int[][]{   new int[] { 8, 63  },
                            new int[]  { 4, 2   }, 
                            new int[]  { 0, -55 }, 
                             new int[] { 8, 53  }, 
                             new int[] { 2, -120}, 
                             new int[] { 8, 57  }  };

      //using LAMBDA expression
      Array.Sort(a, (a1, a2) => { return (a2[0]-a1[0])+((a2[0]-a1[0])==0?(a2[1]-a1[1]):0); 
      });

       Console.WriteLine("LAMBDA Sorting");   
      for(int i=0;i<6;i++)
         Console.WriteLine(" {0}:{1} ",a[i][0],a[i][1]);

      //using LINQ   
      var sorted = from x in a
             orderby x[0] descending ,x[1]  descending
             select x;

       Console.WriteLine("LINQ Sorting");      
       foreach(var item in sorted )
        Console.WriteLine(" {0}:{1} ",item[0], item[1]);
    }

答案 2 :(得分:0)

没有Linq,在范围列中排序索引(FromIndex ... ToIndex):

    public class MyListArrComparer : IComparer<Int32[]>
{
    public Int32 FromIndex {get; set;}
    public Int32 ToIndex {get; set;}
    public int Compare(Int32[] x, Int32[] y)
    {
      for (Int32 index=FromIndex; index<=ToIndex; index++) {
          if (x[index]>y[index]) return -1;
          if (x[index]<y[index]) return 1;
      }
      return 0;
    }
}

您可以添加第三个ASC / DESC参数或列列,而不是范围。

使用示例:

MyListArrComparer comps = new MyListArrComparer();
comps.FromIndex=0;
comps.ToIndex=3;
hhList.Sort(comps);

关于WJ(AK)

相关问题