写程序时经常要管理"一组数据":一个班的分数、购物车里的商品、单词和它的释义。单个变量不够用了,C# 里最常用的两个容器就是 List 和 Dictionary,这篇把它们的日常用法过一遍。
List:会自动伸缩的数组
数组长度是固定的,而 List 会按需自动扩容,用起来最省心:
List<string> fruits = new List<string>();
fruits.Add("苹果"); // 添加到末尾
fruits.Add("香蕉");
fruits.Add("橘子");
fruits.Remove("香蕉"); // 按值移除
Console.WriteLine(fruits.Count); // 输出:2
Console.WriteLine(fruits[0]); // 输出:苹果(和数组一样用下标访问)
也可以在创建时就塞入初始数据:
List<int> scores = new List<int> { 90, 85, 77 };
scores[1] = 88; // 下标直接改
Console.WriteLine(scores.Count); // 输出:3
遍历 List
foreach 是最顺手的遍历方式,不用管下标:
List<string> fruits = new List<string> { "苹果", "橘子" };
foreach (string f in fruits)
{
Console.WriteLine(f); // 依次输出:苹果、橘子
}
Dictionary:按键取值的键值对
Dictionary 存的是"键 → 值"的映射,就像一本真正的字典:按词(键)查释义(值)。
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["小明"] = 18; // 添加或覆盖
ages["小红"] = 20;
Console.WriteLine(ages["小明"]); // 输出:18
Console.WriteLine(ages.Count); // 输出:2
注意:访问不存在的键会直接抛异常,所以取值前要先判断。两种安全写法:
Dictionary<string, int> ages = new Dictionary<string, int> { ["小明"] = 18 };
// 写法一:ContainsKey 判断
if (ages.ContainsKey("小刚"))
{
Console.WriteLine(ages["小刚"]);
}
else
{
Console.WriteLine("查无此人"); // 输出:查无此人
}
// 写法二:TryGetValue,一步到位
if (ages.TryGetValue("小明", out int age))
{
Console.WriteLine(age); // 输出:18
}
遍历字典
遍历时拿到的是一对键值,用 KeyValuePair 接住:
Dictionary<string, int> ages = new Dictionary<string, int>
{
["小明"] = 18, ["小红"] = 20
};
foreach (KeyValuePair<string, int> kv in ages)
{
Console.WriteLine($"{kv.Key} 今年 {kv.Value} 岁");
// 输出:小明 今年 18 岁 / 小红 今年 20 岁
}
小结
- List 是自动扩容的数组:Add 添加、下标访问、Remove 移除、Count 数元素
- Dictionary 是键值对:方括号按键读写,ContainsKey / TryGetValue 用来安全取值
- 有顺序的数据用 List,"按键查找"的场景用 Dictionary
把这两个容器用熟,日常八成的数据管理需求都能应付。以后学到 LINQ,还能对它们做各种查询统计。