2012-08-03 227 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