.NET基类库中是否存在允许使用重复键的字典类?我找到的唯一解决方案是创建,例如,一个类:
Dictionary<string, List<object>>
但实际上用起来很烦人。在Java中,我相信MultiMap可以实现这一点,但在. net中找不到类似的东西。
.NET基类库中是否存在允许使用重复键的字典类?我找到的唯一解决方案是创建,例如,一个类:
Dictionary<string, List<object>>
但实际上用起来很烦人。在Java中,我相信MultiMap可以实现这一点,但在. net中找不到类似的东西。
当前回答
回答了最初的问题。像Dictionary<string, List<object>>这样的东西是在Code项目中一个名为MultiMap的类中实现的。
你可以在下面的链接中找到更多信息: http://www.codeproject.com/KB/cs/MultiKeyDictionary.aspx
其他回答
关于使用Lookup的非常重要的注意事项:
你可以通过调用一个实现IEnumerable(T)的对象上的Lookup(TKey, TElement)实例来创建一个Lookup(TKey, TElement)实例。
没有公共构造函数来创建Lookup(TKey、TElement)的新实例。此外,Lookup(TKey, TElement)对象是不可变的,也就是说,在创建Lookup(TKey, TElement)对象后,您不能从它添加或删除元素或键。
(从MSDN)
我认为这对大多数人来说都是一种阻碍。
当使用List<KeyValuePair<string, object>>选项时,你可以使用LINQ来进行搜索:
List<KeyValuePair<string, object>> myList = new List<KeyValuePair<string, object>>();
//fill it here
var q = from a in myList Where a.Key.Equals("somevalue") Select a.Value
if(q.Count() > 0){ //you've got your value }
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);
}
我用的方法是
词典<弦,弦List < > >
这样,您就有一个键保存一个字符串列表。
例子:
List<string> value = new List<string>();
if (dictionary.Contains(key)) {
value = dictionary[key];
}
value.Add(newValue);
我刚刚遇到了PowerCollections库,其中包括一个名为MultiDictionary的类。它巧妙地包装了这种类型的功能。