简体   繁体   English

将IGrouping转换为IDictionary

[英]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. 我希望分组键的顶部x(而x是用户定义的)作为字典。

For Top 3 I want a Dictionary 对于前三名,我想要一本字典

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

and for Top 2 I want 对于前2名,我想要

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

and for top 1 only 并且仅针对前1名

Key1: 5

How can I convert the IGrouping<int, string> into a IDictionary<string, int> . 如何将IGrouping<int, string>转换为IDictionary<string, int> Note: The Keys are unique. 注意:键是唯一的。

First you get the "Top N" groups by calling Take : 首先,您可以通过调用Take获得“前N个”组:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM