首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# Dictionary 值為 List 時正確添加元素避免鍵衝突

     編輯:程式設計綜合問答

常見錯誤誤區

直接 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

簡潔擴展方法 (C# 7.0+)


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);

進階:一鍵構建 Lookup (替代手動字典)


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>> 更安全、語義更清晰。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved