具有多个具有相同键的条目的字典 [英] A dictionary with multiple entries with the same key
本文介绍了具有多个具有相同键的条目的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个像字典的对象,可以存储多个条目用相同的键。
I need a Dictionary like object that can store multiple entries with the same key. Is this avaliable as a standard collection, or do I need to roll my own?
要澄清,我想要能够做这样的事情:
To clarify, I want to be able to do something like this:
var dict = new Dictionary<int, String>();
dict.Add(1, "first");
dict.Add(1, "second");
foreach(string x in dict[1])
{
Console.WriteLine(x);
}
输出:
first
second
推荐答案
在.NET 3.5中,您可以使用查找而不是字典。
var items = new List<KeyValuePair<int, String>>();
items.Add(new KeyValuePair<int, String>(1, "first"));
items.Add(new KeyValuePair<int, String>(1, "second"));
var lookup = items.ToLookup(kvp => kvp.Key, kvp => kvp.Value);
foreach (string x in lookup[1])
{
Console.WriteLine(x);
}
Lookup
是不可变的。如果您想要可变的版本,您可以使用 EditableLookup noreferrer> MiscUtil 。
The Lookup
class is immutable. If you want a mutable version you can use EditableLookup
from MiscUtil.
这篇关于具有多个具有相同键的条目的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文