概要
public static void Sort(Array array);
で、配列arrayを並び替えることができる。
数値型の配列の時
データは小さい順に並び替えられる。
using System; public class SampleNumSort { public static void Main() { //int型 Console.WriteLine("int型配列{ 2, -1, 5, -3 }の並び替え"); int[] a = new int[] { 2, -1, 5, -3 }; Array.Sort(a); foreach (int i in a) Console.Write($"{i}, "); Console.WriteLine("\n"); //double型 Console.WriteLine("double型配列{ 3.2, -10.5, -2.1, π }の並び替え"); double[] b = new double[] { 3.2, -10.5, -2.1, Math.PI }; Array.Sort(b); foreach (double d in b) Console.Write($"{d}, "); } }
実行結果
int型配列{ 2, -1, 5, -3 }の並び替え -3, -1, 2, 5, double型配列{ 3.2, -10.5, -2.1, π }の並び替え -10.5, -2.1, 3.14159265358979, 3.2,
文字列型の配列の時
ひらがなのとき
五十音順に並び替えられた
using System; public class SampleStringSort { public static void Main() { //ひらがな string[] str = new string[] { "にいがた", "いか", "りんご" }; Array.Sort(str); DisplayString(str); } static void DisplayString(string[] str) { string sum = null; foreach (string s in str) sum += $"{s}, "; Console.Write(sum); } }
実行結果
いか,にいがた,りんご,
アルファベットのとき
A~Zの順に並べ替えられた
また、小文字は大文字よりも前になった。
using System; public class SampleStringSort { public static void Main() { //アルファベット string[] str1 = new string[] { "a", "Aa", "C", "AA", "aa", "A", "aA", "o" }; Array.Sort(str1); DisplayString(str1); } static void DisplayString(string[] str) { string sum = null; foreach (string s in str) sum += $"{s}, "; Console.Write(sum); } }
実行結果
a,A,aa,aA,Aa,AA,C,o,
漢字のとき
熟語の読み方にかかわらず、音読みしたときの五十音順で並び替えられた。
using System; public class SampleStringSort { public static void Main() { string[] str2 = new string[] { "青森", "秋田", "宮城", "北海道" }; string[] str2_2 = new string[] { "氷", "表", "票", "豹" }; string[] str2_3 = new string[] { "西表", "宇宙", "西南" }; Array.Sort(str2); Array.Sort(str2_2); Array.Sort(str2_3); DisplayString(str2); DisplayString(str2_2); DisplayString(str2_3); } static void DisplayString(string[] str) { string sum = null; foreach (string s in str) sum += $"{s}, "; Console.WriteLine(sum); } }
実行結果
北海道,宮城,秋田,青森, 氷,票,表,豹, 宇宙,西南,西表,