简体   繁体   中英

How to create tree like structure

I want to create the data structure like below. 在此输入图像描述

For this one I want go for keyvaluepair structure. 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<>

Your NewStructure would become

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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