KingKerosin
KingKerosin

Reputation: 3841

Convert IGrouping to IDictionary

I have the following grouping as result of a database-query:

5: Key1
3: Key2, Key3, Key4
2: Key5
1: Key6, Key7

I want the top x (whereas x is user-defined) by the groupings key as a dictionary.

For Top 3 I want a Dictionary

Key1: 5
Key2: 3
Key3: 3
Key4: 3
Key5: 2

and for Top 2 I want

Key1: 5
Key2: 3
Key3: 3
Key4: 3

and for top 1 only

Key1: 5

How can I convert the IGrouping<int, string> into a IDictionary<string, int>. Note: The Keys are unique.

Upvotes: 2

Views: 3086

Answers (1)

D Stanley
D Stanley

Reputation: 152556

First you get the "Top N" groups by calling Take:

groups.Take(n)

then flatten to a list of value-key pairs

      .SelectMany(g => g, (g, k) => new {Value = g.Key, Key = k})

then just call ToDictionary:

      .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Upvotes: 5

Related Questions