数组与 List
数组声明/遍历、List<T> 动态列表、集合初始化器、索引 ^1 从末尾
数组与 List
C# 数组是固定长度的,List<T> 是动态的——日常开发中 List 用得更多。
学完本章你将: 掌握数组声明/遍历、List
数组
csharp
// 声明
int[] nums = { 1, 2, 3, 4, 5 };
int[] arr = new int[10]; // 全 0
int[,] matrix = { { 1, 2 }, { 3, 4 } }; // 二维
// 索引(C# 8+ 支持末尾索引)
int last = nums[^1]; // 5(倒数第一个)
int secondLast = nums[^2]; // 4
// 范围(C# 8+)
int[] slice = nums[1..3]; // [2, 3](索引 1 到 3-1)
int[] skipFirst = nums[1..]; // [2,3,4,5]
List
csharp
var list = new List<int> { 1, 2, 3 }; // 集合初始化器
list.Add(4); // [1,2,3,4]
list.AddRange([5, 6]); // [1,2,3,4,5,6]
list.Insert(0, 0); // [0,1,2,3,4,5,6]
list.Remove(3); // 删除值 3
list.RemoveAt(0); // 删除索引 0
bool exists = list.Contains(4); // true
int idx = list.IndexOf(5); // 3
// 遍历
list.ForEach(x => Console.Write(x + " "));
其他集合
csharp
// 不可变集合
System.Collections.Immutable.ImmutableList<int> fixed = [1, 2, 3];
// 只读集合
IReadOnlyList<int> readOnly = list.AsReadOnly();