sbenderli
sbenderli

Reputation: 3794

LINQ Query to create Dictionary of Dictionaries

I have the following schema:

ParentKey | Key | Value

   1       A      3
   1       B      5
   1       C      6
   2       A      4
   2       D      8

I am getting this as an IQueryable<MyObject>

MyObject {
    public int ParentKey{get;set;}
    public String Key{get;set;}
    public int Value{get;set;}
}

I would like to turn this into a Dictionary of dictionaries where ParentKey is the key of the parent dictionary, and key is the key of child dictionary. I am currently doing this in loops, but I'd like to see how it can be done using LINQ.

I am guaranteed that the keys within a particular parent key will always be unique, so no need to worry about or check duplicates keys.

How can I write a LINQ query which will turn this data into a

Dictionary<int, Dictionary<string, int>>

Upvotes: 2

Views: 1229

Answers (1)

D Stanley
D Stanley

Reputation: 152566

You need to group the list by ParentKey first:

list.GroupBy(l => l.ParentKey)
    .AsEnumerable()     // to shift from IQueryable to IEnumerable and hydrate the results
    .ToDictionary(g => g.Key, g => g.ToDictionary(gg => gg.Key, gg => gg.Value));

Upvotes: 12

Related Questions