2013-04-30 102 views
2

我想通過使用字符串以將其複製到新字典中來查找字典 - 看起來應該很簡單,但我不確定語法。使用字符串查找C#字典

基本上它只是:

// the object's myName corresponds to an existing dictionary 
    string stringdic = myName;  

    // here's where I try to create a new dictionary containing the values of the existing dictionary 
    Dictionary<string, int> mySkills = new Dictionary<string, int>(myName); 

這裏的目標就是要與給定的字符串作爲其「名」,並從名字知道哪個出了一套詞典它應該使用創建一個對象 - - 例如,如果myName = Bob,我想在此腳本中訪問字典Bob。

因此,引用預先存在的字典以獲取其鍵/值的其他方式也可以工作。速度不是一個大問題,但我想保持代碼簡單。謝謝!

回答

5

這裏是你怎麼做詞典的詞典:

var persons = new Dictionary<string, Dictionary<string, int>> 
{ 
    { "Jeremy", new Dictionary<string, int> { { "age", 20 }, { "height_cm", 180 } } }, 
    { "Evan", new Dictionary<string, int> { { "age", 18 }, { "height_cm", 167 } } }, 
}; 

Dictionary<string, int> x = persons["Jeremy"]; 
x["age"] = 34; 
+0

謝謝,這對我正在做的事很完美。 – 2013-04-30 01:47:32

2

如果您需要能夠查找字典使用一個字符串,你可以有字典的字典,是這樣的:

using X = Dictionary<string, int>; 

var all = new Dictionary<string, X>(); 

X mySkills = all[myName];