在C#中,KeyValuePair
本身不支持重復的鍵
Dictionary<TKey, List<TValue>>
:var dictionary = new Dictionary<string, List<int>>();
// 添加重復的鍵和值
dictionary.Add("key1", new List<int> { 1, 2, 3 });
dictionary["key1"].Add(4);
// 訪問值
foreach (var key in dictionary.Keys)
{
Console.WriteLine($"Key: {key}");
foreach (var value in dictionary[key])
{
Console.WriteLine($"Value: {value}");
}
}
Lookup<TKey, TValue>
:var list = new List<KeyValuePair<string, int>>
{
new KeyValuePair<string, int>("key1", 1),
new KeyValuePair<string, int>("key1", 2),
new KeyValuePair<string, int>("key2", 3)
};
var lookup = list.ToLookup(kvp => kvp.Key, kvp => kvp.Value);
// 訪問值
foreach (var key in lookup)
{
Console.WriteLine($"Key: {key.Key}");
foreach (var value in key)
{
Console.WriteLine($"Value: {value}");
}
}
這兩種方法都可以處理具有重復鍵的數據。選擇哪一種取決于你的需求和喜好。