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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.