2013-12-19 153 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'來合併中的值。 –