.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;

其他回答

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

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

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

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

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

我用的方法是

词典<弦,弦List < > >

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

例子:

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

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

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

你可以定义一个方法来构建复合字符串键 在任何你想要使用字典的地方,你都必须使用这个方法来构建你的键 例如:

private string keyBuilder(int key1, int key2)
{
    return string.Format("{0}/{1}", key1, key2);
}

使用:

myDict.ContainsKey(keyBuilder(key1, key2))

我使用这个简单的类:

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;