.NET基类库中是否存在允许使用重复键的字典类?我找到的唯一解决方案是创建,例如,一个类:

Dictionary<string, List<object>>

但实际上用起来很烦人。在Java中,我相信MultiMap可以实现这一点,但在. net中找不到类似的东西。


当前回答

我使用这个简单的类:

public class ListMap<T,V> : List<KeyValuePair<T, V>>
{
    public void Add(T key, V value) {
        Add(new KeyValuePair<T, V>(key, value));
    }

    public List<V> Get(T key) {
        return FindAll(p => p.Key.Equals(key)).ConvertAll(p=> p.Value);
    }
}

用法:

var fruits = new ListMap<int, string>();
fruits.Add(1, "apple");
fruits.Add(1, "orange");
var c = fruits.Get(1).Count; //c = 2;

其他回答

回答了最初的问题。像Dictionary<string, List<object>>这样的东西是在Code项目中一个名为MultiMap的类中实现的。

你可以在下面的链接中找到更多信息: http://www.codeproject.com/KB/cs/MultiKeyDictionary.aspx

我用的方法是

词典<弦,弦List < > >

这样,您就有一个键保存一个字符串列表。

例子:

List<string> value = new List<string>();
if (dictionary.Contains(key)) {
     value = dictionary[key];
}
value.Add(newValue);

由于新的c#(我相信它是从7.0开始的),你也可以做这样的事情:

var duplicatedDictionaryExample = new List<(string Key, string Value)> { ("", "") ... }

你使用它作为一个标准的列表,但有两个值命名为任何你想

foreach(var entry in duplicatedDictionaryExample)
{ 
    // do something with the values
    entry.Key;
    entry.Value;
}

你可以添加相同的键与不同的情况,如:

key1 Key1 KEY1 KeY1 kEy1 keY1

我知道这是个愚蠢的答案,但对我来说很管用。

我认为List<KeyValuePair<object object>>可以完成任务。