如何处理KeyValuePair中的重复键
导读:在C#中,KeyValuePair本身不支持重复的键 使用Dictionary<TKey, List<TValue>>: var dictionary = new Dictionary<string, Li...
在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}
");
}
}
这两种方法都可以处理具有重复键的数据。选择哪一种取决于你的需求和喜好。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何处理KeyValuePair中的重复键
本文地址: https://pptw.com/jishu/696998.html
