Alessandro
Alessandro

Reputation: 123

Initialize Nested Dictionaries in c#

I need to know how to access and initialize a series of Dictionaries containing other dictionaries. For example, if I have

class Conv{
    Dictionary<int, Dictionary<int, Dictionary<int, List<double>>>> valori;
}

And I want to initiate the parameter "valori" with random numbers, how can I do it? I would do it like

valori[n1].Values[n2].Values[n3]

But after the first "Value", MVS gives me an error. Maybe I have to allocate the memory first? I learned a little bit of c++, but I'm still new to c# Also let me know if I forgot something important in my question

Upvotes: 1

Views: 3199

Answers (2)

user1781290
user1781290

Reputation: 2874

You need to create the sub-dictionaries for each key before using them

var list = new List<double> {d};
var d1 = new Dictionary<int, List<double>> {{n3, list }};
var d2 = new Dictionary<int, Dictionary<int, List<double>>> {{n2, d1}};
valori[n1] = d2;

You can also write this short in one line:

valori[n1] = new Dictionary<int, Dictionary<int, List<double>>> {{n2, new Dictionary<int, List<double>> {{n3, new List<double> {d}}}}};

When all dictionaries are actually created you can access them normally:

 var savedList = valori[n1][n2][n3];

Since this syntax is very clunky and it is easy to make a mistake (missing if a sub-dictionary exists, overriding data, etc), I'd strongly suggest changing the datastructure or at least hiding it in a dedicated class

Upvotes: 6

MohammadJavadSalehi
MohammadJavadSalehi

Reputation: 41

Maybe i'm mistaken but I can't think of situation that you would need this kind of structure but nevertheless here's my help:

First of all you need to assign the variable or you will get the error : "Use of unassign local variable".So the code will be like:

Dictionary<int, Dictionary<int, Dictionary<int, List<double>>>> valori=new 
Dictionary<int, Dictionary<int, Dictionary<int, List<double>>>>();

Secondly you need to add some data to the dictionary in order to use it later so you should do :

valori.Add(2, new Dictionary<int, Dictionary<int, List<double>>>());
valori.Add(3, new Dictionary<int, Dictionary<int, List<double>>>());
valori.Add(4, new Dictionary<int, Dictionary<int, List<double>>>());

"notice that keys are different"

And instead of new Dictionary<int, Dictionary<int, List<double>>>() you should enter a value of that type.

Upvotes: 1

Related Questions