C# 数组(Array)

声明、初始化、多维与交错数组、以及 `Array` 类的常用方法。

Beginner
Key PointsC# 数组长度固定,创建时就确定;需要动态增删用 `List<T>`。

声明与初始化

C#
int[] a = new int[3];                 // 长度 3,全 0
int[] b = { 1, 2, 3 };
int[] c = new int[] { 1, 2, 3 };
int[] d = [1, 2, 3];                  // C# 12 集合表达式

Console.WriteLine(string.Join(",", a));
Console.WriteLine(string.Join(",", b));
Console.WriteLine(string.Join(",", c));
Console.WriteLine(string.Join(",", d));
Console.WriteLine(b.Length);
Output
0,0,0
1,2,3
1,2,3
1,2,3
3

访问与遍历

C#
int[] arr = { 10, 20, 30, 40 };

Console.WriteLine(arr[0]);
Console.WriteLine(arr[^1]);           // 倒数第一个(C# 8 索引)
Console.WriteLine(arr[1..3].Length);  // 范围(C# 8)

arr[0] = 99;

foreach (var x in arr) Console.Write(x + " ");
Console.WriteLine();

for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
Console.WriteLine();

// 越界会抛异常
try
{
    var _ = arr[10];
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("索引越界");
}
Output
10
40
2
99 20 30 40 
99 20 30 40 
索引越界

^1 means "first from the end"; ^0 is one past the end and cannot be read. 1..3 is a half-open range. Both work on slices and Span too.

多维数组

C#
// 二维:矩形,内存连续
int[,] grid = new int[2, 3];
grid[0, 0] = 1;
grid[1, 2] = 5;

Console.WriteLine(grid.Rank);              // 维数
Console.WriteLine(grid.GetLength(0));      // 行数
Console.WriteLine(grid.GetLength(1));      // 列数

for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 3; j++)
    {
        Console.Write(grid[i, j] + " ");
    }
    Console.WriteLine();
}

// 字面量
int[,] m = { { 1, 2 }, { 3, 4 } };
Console.WriteLine(m[1, 0]);
Output
2
2
3
1 0 0 
0 0 5 
3

交错数组

C#
// 数组的数组,每行长度可以不同
int[][] jagged = new int[3][];
jagged[0] = new[] { 1 };
jagged[1] = new[] { 2, 3 };
jagged[2] = new[] { 4, 5, 6 };

foreach (var row in jagged)
{
    Console.WriteLine(string.Join(",", row));
}

Console.WriteLine(jagged[2][1]);
Output
1
2,3
4,5,6
5
FormMemoryRow lengthsAccess
int[,]连续必须相同a[i, j]
int[][]分散可不同a[i][j]

Array 类的常用方法

C#
int[] nums = { 3, 1, 4, 1, 5 };

Array.Sort(nums);
Console.WriteLine(string.Join(",", nums));

Array.Reverse(nums);
Console.WriteLine(string.Join(",", nums));

Console.WriteLine(Array.IndexOf(nums, 4));

int[] copy = new int[3];
Array.Copy(nums, copy, 3);
Console.WriteLine(string.Join(",", copy));

Array.Clear(copy, 0, copy.Length);
Console.WriteLine(string.Join(",", copy));

// 查找
Console.WriteLine(Array.Exists(nums, x => x > 4));
Console.WriteLine(Array.Find(nums, x => x < 3));
Output
1,1,3,4,5
5,4,3,1,1
1
5,4,3
0,0,0
True
1

Array.Sort mutates in place and is not stable (equal elements may swap). To keep the original, (int[])nums.Clone() first.

数组 vs List

AspectT[]List<T>
长度固定动态
性能最快略慢(有扩容检查)
增删不支持支持
查找手写循环Contains Find 等
Arrays suit fixed, known lengths: seven weekdays, RGB channels, matrix rows. Business data (user lists, order items) almost always wants List<T>.

Friends & Partners