我正在尝试填充字典词典的字典。但是,当我尝试填充我的第三个字典时,我得到以下错误。如何在没有出错的情况下填充第二个字典?
The best overloaded method match for 'System.Collections.Generic.Dictionary<string,System.Collections.Generic.Dictionary<string,
System.Collections.Generic.List<string>>>.this[string]' has some invalid arguments
//code
ClientsData.Add(new MapModel.ClientInfo { Id = IDCounter, Doctors = new Dictionary<string, Dictionary<string,List<string>>>() });
ClientsData[0].Doctors.Add(Reader["DocID"].ToString(), new Dictionary<string,List<string>>());
ClientsData[0].Doctors[0].Add("Name", new List<string>(){ Reader["DocName"].ToString()});//Error occurs here
答案 0 :(得分:1)
要访问类似的字典,您需要使用一个密钥,在您的情况下是一个字符串:
ClientsData[0].Doctors[Reader["DocID"].ToString()].Add("Name", new List<string>(){ Reader["DocName"].ToString()});
答案 1 :(得分:1)
如果您想使用tripple dictonaries,可以使用以下代码段:
var dict = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
dict["level-one"] = new Dictionary<string, Dictionary<string, string>>();
dict["level-one"]["level-two"] = new Dictionary<string, string>();
dict["level-one"]["level-two"]["level-three"] = "hello";
Console.WriteLine(dict["level-one"]["level-two"]["level-three"]);
或者您可以像这样制作自己的包装:
public class TrippleDictionary<TKey, TValue>
{
Dictionary<TKey, Dictionary<TKey, Dictionary<TKey, TValue>>> dict = new Dictionary<TKey, Dictionary<TKey, Dictionary<TKey, TValue>>>();
public TValue this [TKey key1, TKey key2, TKey key3]
{
get
{
CheckKeys(key1, key2, key3);
return dict[key1][key2][key3];
}
set
{
CheckKeys(key1, key2, key3);
dict[key1][key2][key3] = value;
}
}
void CheckKeys(TKey key1, TKey key2, TKey key3)
{
if (!dict.ContainsKey(key1))
dict[key1] = new Dictionary<TKey, Dictionary<TKey, TValue>>();
if (!dict[key1].ContainsKey(key2))
dict[key1][key2] = new Dictionary<TKey, TValue>();
if (!dict[key1][key2].ContainsKey(key3))
dict[key1][key2][key3] = default(TValue);
}
}
并像这样使用它:
var tripple = new TrippleDictionary<string, string>();
tripple["1", "2", "3"] = "Hello!";
Console.WriteLine(tripple["1", "2", "3"]);
请参阅Demo