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

Dictionary<string, List<object>>

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


当前回答

这里有一种方法,用List< KeyValuePair< string, string > >

public class ListWithDuplicates : List<KeyValuePair<string, string>>
{
    public void Add(string key, string value)
    {
        var element = new KeyValuePair<string, string>(key, value);
        this.Add(element);
    }
}

var list = new ListWithDuplicates();
list.Add("k1", "v1");
list.Add("k1", "v2");
list.Add("k1", "v3");

foreach(var item in list)
{
    string x = string.format("{0}={1}, ", item.Key, item.Value);
}

输出k1=v1, k1=v2, k1=v3

其他回答

重复的键将破坏Dictionary的整个契约。在字典中,每个键都是唯一的,并映射到单个值。如果您想要将一个对象链接到任意数量的其他对象,最好的方法可能是类似于DataSet的东西(通常的说法是表)。把键放在一列,值放在另一列。这比字典要慢得多,但这是为了失去散列键对象的能力而付出的代价。

你是说完全一致而不是完全重复吗?否则哈希表将无法工作。

同余意味着两个单独的键可以哈希到等价的值,但键不相等。

例如:假设你的哈希表的哈希函数是hashval = key mod 3。1和4都映射到1,但是是不同的值。这就是列表的概念发挥作用的地方。

当需要查找1时,该值被哈希为1,遍历列表,直到找到Key = 1。

如果允许插入重复的键,则无法区分哪些键映射到哪些值。

我将@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();
    }
  }

List类实际上适用于包含重复项的键/值集合,在此集合上进行迭代。例子:

List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();

// add some values to the collection here

for (int i = 0;  i < list.Count;  i++)
{
    Print(list[i].Key, list[i].Value);
}

这也是可能的:

Dictionary<string, string[]> previousAnswers = null;

这样,我们就有了唯一的键。希望这对你有用。