简体   繁体   English

如何创建树状结构

[英]How to create tree like structure

I want to create the data structure like below. 我想创建如下的数据结构。 在此输入图像描述

For this one I want go for keyvaluepair structure. 对于这个,我想去keyvaluepair结构。 But I am unable to create it. 但我无法创造它。

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

Is it a right way. 这是一种正确的方式。 If so how I can insert values to it. 如果是这样,我如何插入值。 If I insert like 如果我插入像

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

it is giving compile error. 它给出了编译错误。 Nothing comes to my mind. 我什么都没想到。 Any suggestions please. 请给我任何建议。

You can get rid of error by 你可以摆脱错误

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

But probably you`d better try something like this: 但是你最好尝试这样的事情:

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

And then 接着

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

For one, you'll have to initialize each of the dictionaries before you add to them: 首先,在添加每个词典之前,您必须初始化每个词典:

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

But if you know your interior dictionary is only going to have one key value pair then you can do: 但是,如果您知道您的内部字典只有一个键值对,那么您可以这样做:

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

If you are on C# 4.0 , you can accomplish this with a Dictionary<> of KeyValuePair<> 如果您使用的是C# 4.0 ,则可以使用KeyValuePair<>Dictionary<>来完成此操作

Your NewStructure would become 你的NewStructure会成为

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

and you'd use it like this: 你会像这样使用它:

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

With a dictionary of dictionaries you would make each "leaf" a list in itself. 使用词典字典,您可以将每个“叶子”列为自己的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM