2016-03-28 12 views
0

我試圖安排升序二維數組二維數組。此代碼運行一維數組,但我努力實現它的2D,以便它將數組的每一行按升序排列。試圖安排升序C#

1D

public static void Main(string[] args) 
    { 
     int[] sam = { 4, 7, 2, 0 }; 

     Array.Sort(sam); 
     foreach (int value in sam) 
     { 
      Console.Write(value); 
      Console.Write(' '); 
     } 
     Console.WriteLine(); 
    } 

2D

public static void Main(string[] args) 
     { 
      int[] sam = { 4, 7, 2, 0 }, {4, 6, 2, 0}; 

      Array.Sort(sam); 
      foreach (int value in sam) 
      { 
       Console.Write(value); 
       Console.Write(' '); 
      } 
      Console.WriteLine(); 
     } 
+0

你能提供一個例子嗎? –

回答

0

你可以做這樣的事情:

static void Main(string[] args) { 
     int[][] sam = new int[2][]; 
     sam[0] = new int[] {4, 6, 2, 0}; 
     sam[1] = new int[] {4, 7, 2, 0}; 

     foreach(var array in sam) 
     { 
      Array.Sort(array); 
      foreach(var item in array) 
       Console.Write(item+" "); 
      Console.WriteLine(); 
     } 
} 

在這裏,我們宣佈一個二維數組,然後在初始化每個陣列一個時間。然後,我們通過SAM陣列循環,然後分選內它的每個一維數組。

0

有多種解決方案,一個解決方案,我的想法是使用陣列(Jagged Array)的陣列。

比方說,如果你有鋸齒狀的數組定義如下

int[][] numbers2 = new int[][] { 
     new int[]{4,5,6}, 
     new int[]{1,2,3}, 
     new int[]{7,8,9} 
     ... 
    }; 

可以得到排序利用

int[][] sorted = numbers2.Select(x=> string.Join("-", x.ToArray())) 
      .OrderBy(x=>x) 
      .Select(x=> x.Split('-').Select(int.Parse).ToArray())  
      .ToArray(); 

另一種選擇鐵血陣列,讓你的輸入是一個二維數組,你可以做更多或者更少,但輸出被排序Jagged數組。

int[][] sorted_array = numbers.Cast<int>()  
     .Select((x, i) => new { Index = i, Value = x }) 
     .GroupBy(x => x.Index/(numbers.GetUpperBound(0) +1)) 
     .Select(x => string.Join("-", x.Select(v => v.Value))) 
     .OrderBy(x=>x) 
     .Select(x=> x.Split('-').Select(int.Parse).ToArray())  
     .ToArray(); 

這些只是我的選擇,你會是最好的選擇哪個是你的解決方案。

檢查這個Example