2012-08-03 224 views
1

我想創建如下的數據結構。 enter image description here如何創建樹狀結構

對於這個我想要去keyvaluepair結構。但我無法創建它。

public class NewStructure 
{ 
    public Dictionary<string, Dictionary<string, bool>> exportDict; 
} 

這是一個正確的方法。如果是這樣,我可以如何插入值。如果我插入像

NewStructure ns = new NewStructure(); 
ns.exportDict.Add("mainvar",Dictionary<"subvar",true>); 

它給編譯錯誤。 沒有出現在我的腦海裏。任何建議請。

回答

2

您可以通過

Dictionary<string, bool> values = new Dictionary<string, bool>(); 
values.Add("subvar", true); 
ns.exportDict.Add("mainvar", values); 

擺脫錯誤的,不過也許you`d更好的嘗試是這樣的:

class MyLeaf 
{ 
    public string LeafName {get; set;} 
    public bool LeafValue {get; set;} 
} 
class MyTree 
{ 
    public string TreeName {get; set;} 
    public List<MyLeaf> Leafs = new List<MyLeaf>(); 
} 

然後

+0

他還必須初始化'exportDict'字典 – NominSim 2012-08-03 13:24:10

+0

@Jleru ..我想創建2個以上這種類型的對象,並且想要檢索它們。你的例子適合那個嗎? – Searcher 2012-08-03 13:35:12

+0

當然!您可以創建MyTrees列表並根據需要填充它們 – JleruOHeP 2012-08-03 13:53:53

1

首先,你」你必須在添加它們之前初始化每個字典:

exportDict = new Dictionary<string, Dictionary<string, bool>>(); 
Dictionary<string,bool> interiorDict = new Dictionary<string,bool>(); 
interiorDict.Add("subvar", true); 
exportDict.Add("mainvar", interiorDict); 

但是,如果你知道你的內部字典只會有一個鍵值對,那麼你可以這樣做:

exportDict = new Dictionary<string, KeyValuePair<string,bool>>(); 
exportDict.Add("mainvar", new KeyValuePair<string,bool>("subvar", true)); 
1

如果您對C# 4.0,你可以做到這點Dictionary<>KeyValuePair<>

NewStructure將成爲

public class NewStructure 
{ 
    public Dictionary<string, KeyValuePair<string, bool>> exportDict = 
     new Dictionary<string, KeyValuePair<string, bool>>(); //this is still a dictionary! 
} 

,你會使用這樣的:

NewStructure ns = new NewStructure(); 
ns.exportDict.Add("mainvar",new KeyValuePair<string,bool>("subvar",true)); 

使用詞典的字典,你會使每個「葉」列表本身。

+0

我們是否應該將Dictionary對象的exportDict設置爲'KeyValuePair'類型? – Searcher 2012-08-03 13:24:00

+0

不,exportDict仍然是一個字典。我添加了它的初始化完整性。 – Alex 2012-08-03 13:33:43