Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Dictionary of Dictionaries [closed]

I'm to create a dictionary of dictionaries of in LINQ matched on a parent id.

I have a data model

 Pseudo-Model:
    Int ID;
    Int Namel
    Int? ParentID;

I want to create a Dictionary Of Dictonaries. The first Dictionary is the ID of those whose are only a parent and the dictionary with-in it would contain the ID, Name.

I know I could do this through a looping but I want to figure out how to do it though LINQ.

like image 446
johnny 5 Avatar asked Dec 04 '25 13:12

johnny 5


1 Answers

GroupBy creates an IGrouping with a Key value that you can iterate over (or make additional LINQ calls on).

ToDictionary takes two selectors - one for the key and one for the value. The key for the outer dictionary is ParentID and the value is another dictionary, whose key is ID and value is Name.

Assuming that ID is unique (at least within a ParentID group) you can do:

 _model.Terrtories
       .GroupBy(i => i.ParentID.HasValue ? i.ParentID.Value : 0)   
       .ToDictionary(g => g.Key,   // outer dictionary key
                     g => g.ToDictionary(i => i.ID,   // inner dictionary key
                                         i => i.Name));  // inner dictionary value

Note that the second parameter to the outer ToDictionary is translating the items within each group into an inner dictionary.

like image 69
D Stanley Avatar answered Dec 08 '25 06:12

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!