如何处理KeyValuePair中的重复键

   2024-09-30 9530
核心提示:在C#中,KeyValuePair本身不支持重复的键使用DictionaryTKey, ListTValue:var dictionary = new Dictionarystring, Listint();/

在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}");    }}

这两种方法都可以处理具有重复键的数据。选择哪一种取决于你的需求和喜好。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号