How to use nested dictionary in C #?

My requirement

Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>>

When I try to get the value of the internal dictionary using the key (externalString), it gives the error message "indexing with expression type cannot be applied ...............".

I tried this

Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>> dict1 = new
    Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>>;

Dictionary<innerString, List<SelectListItem>> dict2 = dict1.values["outerString"];

Any quick help would be greatly appreciated.

thanks in advance.

+3
source share
7 answers

I assume you just need to:

Dictionary<innerString, List<SelectListItem>> dict = dict1["someKey"];
+6
source

You just need to change the last line of your code snippet (I assumed that you wrote the inner line and the outer line, which you should designate as a line):

var dict = dict1["someValue"];

Also, you could probably make your code very readable with the var keyword:

var dict1 = new Dictionary<string, Dictionary<string, List<SelectListItem>>>();
var dict = dict1["someValue"];
+3
source

, outerString innerString ? stringstringList<SelectListItem>? , string, ...

+2
source

You were close:

Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>> dict1 = new 
Dictionary<outerString, Dictionary<innerString, List<SelectListItem>>>(); 

// Get inner dictionary whose key is "someValue"
Dictionary<innerString, List<SelectListItem>> dict = dict1["someValue"]
+2
source

I misunderstood you? It works great

Dictionary<string, Dictionary<string, List<string>>> list = new Dictionary<string, Dictionary<string, List<string>>>();
list.Add("test", new Dictionary<string, List<string>>());
Dictionary<string, List<string>> inner = list["test"];

or

var list = new Dictionary<string, Dictionary<string, List<string>>>();
list.Add("test", new Dictionary<string, List<string>>());
Dictionary<string, List<string>> inner = list["test"];
+1
source

IN

Dictionary<string, Dictionary<string, List<T>> dict1 = 
    new Dictionary<string, Dictionary<string, List<T>>();

you need

List<T> list12 = dict1["key1"]["key2"];

List<int> list1 = new List<int>();
list1.Add(1);
list1.Add(2);

Dictionary<string, List<int>> innerDict = new Dictionary<string, List<int>>();
innerDict.Add("inner", list1);

Dictionary<string, Dictionary<string, List<int>>> dict1 =
    new Dictionary<string, Dictionary<string, List<int>>>();
dict1.Add("outer", innerDict);

List<int> list2 = dict1["outer"]["inner"];
0
source

How about you use an array of strings for the key, rather than trying to insert dictionaries -

       Dictionary<string[], List<string>> dict = 
           new Dictionary<string[],List<string>>();

       string[] key = {"inner", "outer"};
       List<string> vals = new List<string>();

       dict.Add(key, vals);
0
source

Source: https://habr.com/ru/post/1728621/


All Articles