几乎所有C#开发者都使用过Dictionary<TKey, TValue>
,但说实话——你真的发挥了这个强大数据结构的全部潜力吗?本文将展示多数人仅停留在Add()
和ContainsKey()
的基础用法,而字典还有许多特性能让代码更简洁、性能更优、功能更强大。
var countryCodes = new Dictionary<string, string>
{
{"US", "United States"},
{"BD", "Bangladesh"},
{"IN", "India"}
}
这是最基础的字符串键值对字典,但真正的威力远不止于此。
常见反模式:
if (countryCodes.ContainsKey("IN"))
{
var value = countryCodes["IN"]; // 二次查找
}
✅ 最佳实践:
if (countryCodes.TryGetValue("IND", out string value))
{
Console.WriteLine(value); // 只需一次查找
}
这个改动能避免不必要的二次查找,在大字典上性能差异显著。
var studentMarks = new Dictionary<string, Dictionary<string, int>>
{
["Raj"] = new Dictionary<string, int> {
["Math"] = 90, ["Physics"] = 85
},
["Karim"] = new Dictionary<string, int> {
["Math"] = 80, ["Physics"] = 75
}
};
var topSubjects = studentMarks["Rahim"]
.Where(kvp => kvp.Value > 80)
.Select(kvp => kvp.Key);
var students = new[]
{
new { Id = 1, Name = "Raj" },
new { Id = 2, Name = "Karim" }
};
var studentDict = students.ToDictionary(s => s.Id, s => s.Name);
var val = countryCodes.GetValueOrDefault("JP", "Not Found"); // .NET Core 2.0+
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
dict["IND"] = "India";
Console.WriteLine(dict["ind"]); // 输出: India
var country = code switch
{
"US" => "United States",
"IND" => "India",
_ => "Unknown"
};
通过合理运用TryGetValue
、LINQ、嵌套字典、自定义比较器和ToDictionary()
等方法,你可以轻松将字典的威力提升到全新水平。这个被低估的数据结构,值得每个C#开发者深入掌握。