2.5 KiB
2.5 KiB
第七课:集合(List / Dictionary)
List 动态数组
T 是泛型,占位符,使用时替换成具体类型。
using System.Collections.Generic;
// 声明
List<string> names = new List<string>();
// 添加
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);
}
初始化器
// 声明时直接填充
List<string> fruits = new List<string>()
{
"苹果", "香蕉", "橙子"
};
// 简写(C# 12+)
List<string> fruits2 = ["苹果", "香蕉", "橙子"];
常用方法
List<int> numbers = new List<int>() { 3, 1, 4, 1, 5 };
numbers.Sort(); // 排序
numbers.Reverse(); // 反转
numbers.Contains(5); // 是否包含
numbers.IndexOf(4); // 查找索引
numbers.Clear(); // 清空
numbers.InsertRange(0, ...); // 插入集合
Dictionary<K, V> 键值对
using System.Collections.Generic;
// 声明
Dictionary<string, int> scores = new Dictionary<string, int>();
// 添加
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<string, int> kv in scores)
{
Console.WriteLine($"{kv.Key}: {kv.Value}");
}
// 只遍历键或值
foreach (string key in scores.Keys) { }
foreach (int value in scores.Values) { }
Dictionary 初始化
// C# 6+
Dictionary<string, int> config = new Dictionary<string, int>()
{
["sensitivity"] = 70,
["volume"] = 80,
["language"] = 1
};
List 和 Dictionary 在项目中的应用
// 识别结果历史
List<string> transcriptHistory = new List<string>();
// 设备配置
Dictionary<string, string> deviceConfig = new Dictionary<string, string>()
{
["name"] = "USB麦克风",
["sampleRate"] = "16000",
["channels"] = "1"
};
// 设置选项
Dictionary<string, bool> settings = new Dictionary<string, bool>()
{
["autoConnect"] = true,
["vad"] = true
};