.NET Framework 4より導入されたStructuralComparisons.StructuralComparerを使うことでもジャグ配列をソートすることが出来ます。 ただし、ソート出来るのはジャグ配列内の各配列の長さが等しい場合(=矩形のジャグ配列)に限られます。
次の例は、StructuralComparisons.StructuralComparerを使って2段のジャグ配列をソートする例です。
StructuralComparisons.StructuralComparerを使って2段の矩形ジャグ配列をソートする
using System;
using System.Collections;
class Sample {
static void Main()
{
var arr = new int[][] {
new int[] {1, 2, 1},
new int[] {2, 1, 1},
new int[] {2, 2, 1},
new int[] {2, 1, 1},
new int[] {2, 1, 2},
new int[] {1, 2, 3},
new int[] {1, 1, 1},
new int[] {1, 2, 2},
};
// StructuralComparisons.StructuralComparerを指定してジャグ配列をソート
Array.Sort(arr, StructuralComparisons.StructuralComparer);
for (var y = 0; y < arr.Length; y++) {
for (var x = 0; x < arr[y].Length; x++) {
Console.Write("{0}, ", arr[y][x]);
}
Console.WriteLine();
}
}
}
実行結果
1, 1, 1, 1, 2, 1, 1, 2, 2, 1, 2, 3, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 2, 1,
StructuralComparisonsについては構造の比較で詳しく解説しています。