具有相同键的多个条目的字典
我需要一个类似字典的对象,它可以使用相同的键存储多个条目。这是一个标准集合,还是我需要推出自己的集合?
为了澄清,我希望能够做这样的事情:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 .NET 3.5 中,您可以使用 查找 而不是字典。
Lookup
类是不可变的。如果您想要可变版本,可以使用 MiscUtilEditableLookup >。In .NET 3.5 you can use a Lookup instead of a Dictionary.
The
Lookup
class is immutable. If you want a mutable version you can useEditableLookup
from MiscUtil.我建议这样做:
I would recommend doing something like this:
Dictionary
不支持此类行为,并且基类库中没有提供此类行为的集合。最简单的方法是构造一个像这样的复合数据结构:作为第二个参数,您应该使用一个集合,它提供您正在寻找的品质,即稳定的顺序⇒等
List
,快速访问<代码>HashSetDictionary<T,K>
does not support such behavior and there's no collection in the base class library providing such behavior. The easiest way is to construct a composite data structure like this:As the second parameter you should use a collection which provides the qualities you are looking for, i.e. stable order ⇒
List<T>
, fast accessHashSet<T>
, etc.您肯定想使用 NameValueCollection:
using System.Collections.Specialized;
You definitely want to use NameValueCollection:
using System.Collections.Specialized;
您正在寻找的实际上并不是传统意义上的字典(请参阅 关联数组 )。
据我所知,框架中没有提供此功能的类(
System.Linq.Lookup
不公开构造函数),但您可以自己创建一个实现ILookup
What you're looking for isn't actually a Dictionary in the traditional sense (see Associative Array).
There's no class, as far as I'm aware, that offers this in the framework (
System.Linq.Lookup
doesn't expose a constructor), but you could create a class yourself that implementsILookup<TKey, TElement>
您也许可以在主键上使用字典,其中每个元素都是辅助键上的列表或其他集合。要将项目添加到数据结构中,请查看主键是否存在。如果没有,请使用您的值创建一个新的单项列表并将其存储在字典中。如果主键确实存在,请将您的值添加到字典中的列表中。
You could perhaps use a Dictionary on your primary key, in which each element is a List or other collection on your secondary key. To add an item to your data structure, see if the primary key exists. If not, create a new single-item list with your Value and store it in the dictionary. If the primary key does exist, add your Value to the list that's in the dictionary.