在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}"); }}这两种方法都可以处理具有重复键的数据。选择哪一种取决于你的需求和喜好。


