温馨提示×

如何处理KeyValuePair中的重复键

小樊
83
2024-09-03 12:23:45
栏目: 编程语言

在C#中,KeyValuePair本身不支持重复的键

  1. 使用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}");
    }
}
  1. 使用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}");
    }
}

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

0