C# 具有重复键的字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13184698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:44:05  来源:igfitidea点击:

Dictionary with duplicate Key

c#.net-3.5c#-3.0

提问by Yograj Gupta

Possible Duplicate:
Is there an alternative to Dictionary/SortedList that allows duplicates?

可能的重复:
是否有允许重复的字典/排序列表的替代方法?

I am looking for a Dictionary sort of class which can have duplicate Keys.

我正在寻找一个字典类,它可以有重复的键。

I search about it, and found LookUp class can use to store duplicate keys, but It has no default constructor, So we can't initialize it without any other object to LookUp.

我搜索了一下,发现LookUp类可以用来存储重复键,但是它没有默认构造函数,所以我们不能在没有任何其他LookUp对象的情况下初始化它。

But I have no any such object initially from which I can initialize a LookUp object.

但是我最初没有任何这样的对象,我可以从中初始化一个 LookUp 对象。

So, My question is, Is there any class in .Net framework 3.5, which behave like Dictionary but allow me to have duplicate keys like LookUp?

所以,我的问题是,.Net 框架 3.5 中是否有任何类,其行为类似于 Dictionary 但允许我拥有像 LookUp 这样的重复键?

采纳答案by Servy

A Dictionary, by definition, will never be able to have multiple keys with the same value. (If you looked up a key whatever would you return?) Even a Lookup, which you refer to, doesn't allow it. What you cando is have each key refer to multiple values(logically, not technically). This is done by having a dictionary in which the value is a data structure of some sort (for example, a List) that contains all of the values that correspond to that particular key.

根据定义,Dictionary 永远无法拥有多个具有相同值的键。(如果您查找键,您会返回什么?)即使是您所指的查找,也不允许这样做。您可以做的是让每个键引用多个值(逻辑上,而不是技术上)。这是通过拥有一个字典来完成的,其中的值是某种类型的数据结构(例如, a List),其中包含与该特定键对应的所有值。

回答by madeFromCode

You could create a list of key value pairs.

您可以创建一个键值对列表。

List<KeyValuePair<string,int>>

回答by Albin Sunnanbo

You can compose a type yourself by using a dictionary of lists, Dictionary<TKey, List<TValue>>

您可以使用列表字典自己编写类型, Dictionary<TKey, List<TValue>>

You can create a class inheriting from that class and add suitable add-methods etc that handles creating a new list for the first item on a given key.

您可以创建一个继承自该类的类,并添加合适的 add-methods 等来处理为给定键上的第一项创建新列表。