LINQ中的GroupBy如何工作? [英] How does GroupBy in LINQ work?

查看:116
本文介绍了LINQ中的GroupBy如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最初有一个<string, List<ProviderSummary>>字典,称为rowsDictionary

I originally have a dictionary of <string, List<ProviderSummary>> called rowsDictionary

现在,对于该词典的每个键,我都按以下标准将其值列表分组:

Now for each key of that dictionary I group its list of values by some criteria as below:

    Dictionary<string, List<ProviderSummary>> providerGroups = rowsDictionary.ToDictionary(
            x => x.Key,
            v => v.Value.GroupBy(x => new { x.GroupID, x.GroupFin, x.ZipCode })
                      .Select(x => x.First())
                      .ToList());

因此,例如,如果key["1234"]最初在其值列表中有6个项目,则根据该分组现在可能有两个项目.我的问题和困惑是,其余的价值观会怎样? (这四个),将为该组返回的这两个列表输入什么值?

so for example if key["1234"] originally had 6 items in its list of values, now it may have two items based on that grouping. My question and confusion is what happens to the rest of the values? ( those four) and what values will go in to these two lists that are returned for the group?

推荐答案

分组方式是将您要分组的所有内容放入与您在group by子句中指定的键匹配的项的集合中.

Group by works by taking whatever you are grouping and putting it into a collection of items that match the key you specify in your group by clause.

如果您具有以下数据:

Member name     Group code
Betty           123
Mildred         123
Charli          456
Mattilda        456

以及以下查询

var query = from m in members
            group m by m.GroupCode into membersByGroupCode
            select membersByGroupCode;

group by将返回以下结果:

The group by will return the following results:

您通常不希望直接选择分组.如果我们只希望组代码和成员名而不包含所有其他多余的数据怎么办?

You wouldn’t typically want to just select the grouping directly. What if we just want the group code and the member names without all of the other superfluous data?

我们只需要执行一次选择就可以得到我们想要的数据:

We just need to perform a select to get the data that we are after:

var query = from m in members
            group m by m.GroupCode into membersByGroupCode
            let memberNames = from m2 in membersByGroupCode
                              select m2.Name
            select new
            {
                GroupCode = membersByGroupCode.Key,
                MemberNames = memberNames
            };

哪个返回以下结果:

这篇关于LINQ中的GroupBy如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆