如何创建树状结构

时间:2012-08-03 13:17:03

标签: c# data-structures

我想创建如下的数据结构。 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>);

它给出了编译错误。 我什么都没想到。请给我任何建议。

3 个答案:

答案 0 :(得分:2)

你可以通过

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

但是你最好尝试这样的事情:

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>();
}

然后

MyTree myTree = new MyTree();
myTree.TreeName = "mainvar";
myTree.Leafs.Add(new MyLeaf() {LeafName = "subvar", LeafValue = true});

答案 1 :(得分: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));

答案 2 :(得分: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));

使用字典词典,您可以将每个“叶子”列为一个列表。

相关问题