Reputation: 1855
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.
Upvotes: 1
Views: 690
Reputation: 23290
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.
Upvotes: 1
Reputation: 10386
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});
Upvotes: 2
Reputation: 8511
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));
Upvotes: 1