C# -- 交错数组的使用
C# -- 交错数组的使用
交错数组是元素为数组的数组。交错数组元素的维度和大小可以不同。交错数组有时称为“数组的数组”。
1. 举例一:子数组是长度相同的一维数组
static void Main(string[] args) { string[][] week = new string[3][]; week[0] = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; week[1] = new string[] { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; week[2] = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; for (int i = 0; i < week.Length; i++) { Console.WriteLine("----------------------------------------------------------------"); Console.Write("第" + (i + 1).ToString() + "个数组的值:"); for (int j = 0; j < week[i].Length; j++) { Console.Write(week[i][j] + ","); } Console.WriteLine(); } Console.ReadKey(); }
2. 举例二:子数组是长度不同的一维数组
static void Main(string[] args) { int[][] number = new int[3][]; number[0] = new int[] { 1, 3, 5, 7, 9 }; number[1] = new int[] { 0, 2, 4, 6, 8 }; number[2] = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; for (int i = 0; i < number.Length; i++) { Console.WriteLine("----------------------------------------------------------------"); Console.Write("第" + (i + 1).ToString() + "个数组的值:"); for (int j = 0; j < number[i].Length; j++) { Console.Write(number[i][j] + ","); } Console.WriteLine(); } Console.ReadKey(); }
3. 举例三:子数组是长度不同的二维数组
static void Main(string[] args) { string[][,] numberX = new string[3][,]; numberX[0] = new string[2, 2] { { "A", "A" }, { "B", "B" } }; numberX[1] = new string[3, 3] { { "A", "A", "A" }, { "B", "B", "B" }, { "C", "C", "C" } }; numberX[2] = new string[4, 4] { { "A", "A", "A", "A" }, { "B", "B", "B", "B" }, { "C", "C", "C", "C" }, { "D", "D", "D", "D" } }; for (int i = 0; i < numberX.Length; i++) { Console.WriteLine("----------第" + (i + 1).ToString() + "个二维数组--------------------------"); for (int j = 0; j < Math.Sqrt(numberX[i].Length); j++) { for (int k = 0; k < Math.Sqrt(numberX[i].Length); k++) { Console.Write(numberX[i][j, k] + " "); } Console.WriteLine(); } } Console.ReadKey(); }