用相同的密钥多个条目的字典 [英] A dictionary with multiple entries with the same key
本文介绍了用相同的密钥多个条目的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要像可存储与相同的密钥多个条目对象的字典。 ?这是avaliable为标准集合,或是否需要推出自己的
要澄清,我希望能够做这样的事:
VAR字典=新词典< INT,字符串>();
dict.Add(1,第一);
dict.Add(1,第二);
的foreach(字典中的字符串x [1])$ B $ B {
Console.WriteLine(x)的;
}
输出:
第一
第二
解决方案
在.NET 3.5,您可以使用查找而不是一个字典。
VAR项目=新的List< KeyValuePair< INT,字符串>>();
items.Add(新KeyValuePair< INT,字符串>(1,第一));
items.Add(新KeyValuePair< INT,字符串>(1,第二));
VAR查找= items.ToLookup(KVP => kvp.Key,KVP => kvp.Value);
的foreach(在查找字符串x [1])$ B $ B {
Console.WriteLine(x)的;
}
的
查找
类是不可改变的。如果你想要一个可变的版本,你可以使用 EditableLookup
通过 MiscUtil 一>
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);
}
Output:
first
second
解决方案
In .NET 3.5 you can use a Lookup instead of a Dictionary.
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);
}
The Lookup
class is immutable. If you want a mutable version you can use EditableLookup
from MiscUtil.
这篇关于用相同的密钥多个条目的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文