2013-12-19 126 views
0

我想填充词典的词典字典。但是,当我尝试填充我的第三个词典时,我得到下面的错误。我如何填充我的第二个字典而不会出现错误?如何填充字典字典词典?

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 
+3

我会扔了这一点还有:这是一个巨大的代码味道。我会说大设计问题。 –

+0

你会更好地做一个自定义'结构ComplexKey',它执行必要的相等/散列代码魔术来充当* one *字典的关键字。 –

回答

1

要访问的字典一样,你需要使用一个密钥,你的情况是一个字符串:

ClientsData[0].Doctors[Reader["DocID"].ToString()].Add("Name", new List<string>(){ Reader["DocName"].ToString()}); 
+0

这就是说,我同意@西蒙的评论,你可能想重新考虑你的设计...... – Alden

1

如果你想使用特里普尔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

+0

'ContainsKey'是间接的。使用'TryGetValue'和'Add'来合并中的值。 –