2016-03-28 54 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