2015-04-21 19 views
1

我有具有下列值的多維數組排序多維數組:C#按多個列

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 

什麼是做到這一點的最好方法是什麼?

+0

的可能重複(http://stackoverflow.com/questions/ [我怎麼排序在C#中的二維數組?] 232395/how-do-i-sort-a-two-dimensional-array-in-c) –

+0

@AlexShesterov這個問題似乎只包含一次一列的排序,我需要一次排列兩個。 –

+0

如果你想使用原始的int數組,寫入自定義排序程序! http://en.wikipedia.org/wiki/Sorting_algorithm。這是一個學校作業 – rpc1

回答

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

 
     } 
 
    } 
 
}

+0

這很好,謝謝! –

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]); 
    } 
+0

也很好,謝謝! –

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參數或列表o f列而不是範圍。

使用例如:

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

問候WJ(AK)