直接 dict[key].Add(value) 會拋出 KeyNotFoundException,因鍵不存在時無法訪問值集合。
var dict = new Dictionary<string, List<int>>();
string key = "group1";
int value = 42;
// 寫法 1:TryGetValue + 實例化 (推薦,單線程)
if (!dict.TryGetValue(key, out var list)) {
list = new List<int>();
dict[key] = list;
}
list.Add(value);
// 寫法 2:GetOrAdd (System.Collections.Concurrent 並發安全)
var concurrentDict = new ConcurrentDictionary<string, List<int>>();
concurrentDict.GetOrAdd(key, _ => new List<int>()).Add(value); // 注意:List 非線程安全,高併發需鎖或用 ConcurrentBag
public static class DictExtensions {
public static void AddToList<TKey, TValue>(
this Dictionary<TKey, List<TValue>> dict, TKey key, TValue value) {
if (!dict.TryGetValue(key, out var list)) {
list = new List<TValue>();
dict[key] = list;
}
list.Add(value);
}
}
// 使用
dict.AddToList("group1", 42);
var items = new[] { ("A", 1), ("B", 2), ("A", 3) };
var lookup = items.ToLookup(kv => kv.Item1, kv => kv.Item2);
// lookup["A"] → IEnumerable<int> {1, 3},唯讀、自動分組、無鍵不存在異常
ILookup<TKey, TValue> 專為「一鍵多值」設計,比手維護 Dictionary<TKey, List<TValue>> 更安全、語義更清晰。