# 第七课:集合(List / Dictionary) ## List 动态数组 `T` 是泛型,占位符,使用时替换成具体类型。 ```csharp using System.Collections.Generic; // 声明 List names = new List(); // 添加 names.Add("无言势"); names.Add("字幕"); names.Add("工具"); // 插入(指定位置) names.Insert(1, "新插入"); // 删除 names.Remove("字幕"); names.RemoveAt(0); // 按索引删除 // 访问 string first = names[0]; // 数量 int count = names.Count; // 遍历 foreach (string name in names) { Console.WriteLine(name); } ``` ## 初始化器 ```csharp // 声明时直接填充 List fruits = new List() { "苹果", "香蕉", "橙子" }; // 简写(C# 12+) List fruits2 = ["苹果", "香蕉", "橙子"]; ``` ## 常用方法 ```csharp List numbers = new List() { 3, 1, 4, 1, 5 }; numbers.Sort(); // 排序 numbers.Reverse(); // 反转 numbers.Contains(5); // 是否包含 numbers.IndexOf(4); // 查找索引 numbers.Clear(); // 清空 numbers.InsertRange(0, ...); // 插入集合 ``` ## Dictionary 键值对 ```csharp using System.Collections.Generic; // 声明 Dictionary scores = new Dictionary(); // 添加 scores["无言势"] = 100; scores["玩家A"] = 85; scores.Add("玩家B", 90); // 访问 int score = scores["无言势"]; // 100 // 安全访问(键不存在不报错) scores.TryGetValue("不存在", out int value); // 是否包含键 if (scores.ContainsKey("无言势")) { Console.WriteLine(scores["无言势"]); } // 删除 scores.Remove("玩家A"); // 遍历 foreach (KeyValuePair kv in scores) { Console.WriteLine($"{kv.Key}: {kv.Value}"); } // 只遍历键或值 foreach (string key in scores.Keys) { } foreach (int value in scores.Values) { } ``` ## Dictionary 初始化 ```csharp // C# 6+ Dictionary config = new Dictionary() { ["sensitivity"] = 70, ["volume"] = 80, ["language"] = 1 }; ``` ## List 和 Dictionary 在项目中的应用 ```csharp // 识别结果历史 List transcriptHistory = new List(); // 设备配置 Dictionary deviceConfig = new Dictionary() { ["name"] = "USB麦克风", ["sampleRate"] = "16000", ["channels"] = "1" }; // 设置选项 Dictionary settings = new Dictionary() { ["autoConnect"] = true, ["vad"] = true }; ```