一次元配列の長さの取得
配列名.Lengthで配列の長さを取得する。
using System; public class SampleLength { public static void Main() { int[] a = new int[4] { 3, 2, 1, 5 }; Console.WriteLine(a.Length); } }
実行結果
4
二次元配列の長さの取得
配列名.Lengthで配列の全体の長さを、
配列名.GetLength(n)で配列のn次元の長さを取得する
using System; public class SampleLength2 { public static void Main() { int[,] a = new int[,] { { 3, 4, 6 }, { 1, 2, 5 } }; Console.WriteLine(a.Length); Console.WriteLine(a.GetLength(0)); Console.WriteLine(a.GetLength(1)); } }
実行結果 6 2 3
使用例
一次元配列のソート
using System; public class SampleLength3 { public static void Main() { int[] a = new int[4] { 3, 2, 1, 5 }; //ソート for (int i = 0; i < a.Length; i++) { for (int j = i + 1; j < a.Length; j++) { if (a[i] > a[j]) { int tmp = a[j]; a[j] = a[i]; a[i] = tmp; } } } //結果の表示 foreach (int i in a) Console.Write(i + ","); } }
実行結果 1,2,3,5,
2次元配列の表示
using System; public class SampleLength4 { public static void Main() { int[,] a = new int[,] { { 3, 4, 6 }, { 1, 2, 5 } }; for (int i = 0; i < a.GetLength(0); i++) { for (int j = 0; j < a.GetLength(1); j++) { Console.Write(a[i, j] + ","); } Console.Write("\n"); } } }
実行結果 3,4,6, 1,2,5,