LINQ Dictionary of Dictionaries

c#, dictionary, linq

Solution

`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.

Problem

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.

Original source