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

Dictionary<string, List<object>>

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


当前回答

我用的方法是

词典<弦,弦List < > >

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

例子:

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

其他回答

我用的方法是

词典<弦,弦List < > >

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

例子:

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

我将@Hector Correa的答案更改为具有泛型类型的扩展,并添加了一个自定义TryGetValue。

  public static class ListWithDuplicateExtensions
  {
    public static void Add<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)
    {
      var element = new KeyValuePair<TKey, TValue>(key, value);
      collection.Add(element);
    }

    public static int TryGetValue<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> collection, TKey key, out IEnumerable<TValue> values)
    {
      values = collection.Where(pair => pair.Key.Equals(key)).Select(pair => pair.Value);
      return values.Count();
    }
  }

由于新的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;
}

关于使用Lookup的非常重要的注意事项:

你可以通过调用一个实现IEnumerable(T)的对象上的Lookup(TKey, TElement)实例来创建一个Lookup(TKey, TElement)实例。

没有公共构造函数来创建Lookup(TKey、TElement)的新实例。此外,Lookup(TKey, TElement)对象是不可变的,也就是说,在创建Lookup(TKey, TElement)对象后,您不能从它添加或删除元素或键。

(从MSDN)

我认为这对大多数人来说都是一种阻碍。

如果同时使用字符串作为键和值,则可以使用System.Collections.Specialized。它将通过GetValues(string key)方法返回一个字符串值数组。