c# - LINQ 中的 GroupBy 是如何工作的?

标签 c# linq linq-group

我原来有一本<string, List<ProviderSummary>>的字典称为 rowsDictionary

现在,对于该字典的每个键,我按以下一些标准对其值列表进行分组:

    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 个项目,现在它可能有两个基于该分组的项目。我的问题和困惑是其余的值(value)观会发生什么? (这四个)什么值将进入为组返回的这两个列表?

最佳答案

Group by 的工作方式是将要分组的任何内容放入与您在 group by 子句中指定的键匹配的项目集合中。

如果你有以下数据:

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;

分组依据将返回以下结果:

enter image description here

您通常不想直接选择分组。如果我们只想要组代码和成员名称而不需要所有其他多余数据怎么办?

我们只需要执行一个选择来获取我们想要的数据:

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
            };

返回以下结果:

enter image description here

关于c# - LINQ 中的 GroupBy 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25140623/

相关文章:

c# - 清空列表<string>

c# - 将类的属性映射到接口(interface)

c# - 如何扫描网络以查找特定外设

c# - 查询日期而不是日期时间 docdb

c# - 处理 SQL 命令并关闭连接

c# - 如何按日期排序前 10 个不同的行

c# - IEnumerable<> 到 IList<>

c# - LINQ 按自定义类型分组不起作用

c# - Linq 按日期分组(月)

c# - 将具有匹配属性的对象分组到列表中