.NET基类库中是否存在允许使用重复键的字典类?我找到的唯一解决方案是创建,例如,一个类:
Dictionary<string, List<object>>
但实际上用起来很烦人。在Java中,我相信MultiMap可以实现这一点,但在. net中找不到类似的东西。
.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;
其他回答
NameValueCollection支持一个键(也是字符串)下的多个字符串值,但这是我所知道的唯一一个例子。
当我遇到需要这种功能的情况时,我倾向于创建类似于您示例中的结构。
当使用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 }
由于新的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;
}
你可以定义一个方法来构建复合字符串键 在任何你想要使用字典的地方,你都必须使用这个方法来构建你的键 例如:
private string keyBuilder(int key1, int key2)
{
return string.Format("{0}/{1}", key1, key2);
}
使用:
myDict.ContainsKey(keyBuilder(key1, key2))
这也是可能的:
Dictionary<string, string[]> previousAnswers = null;
这样,我们就有了唯一的键。希望这对你有用。