2

我原本有一本<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());

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?

4

3 回答 3

7

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;

group by 将返回以下结果:

在此处输入图像描述

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

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

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

它返回以下结果:

在此处输入图像描述

于 2014-08-05T14:20:35.253 回答
4

为组返回的列表中将包含哪些值?

每个组的第一个,因为您这样做:

.Select(x => x.First())

其余的值会发生什么?

它们不会被投影到您的目标词典中。

于 2014-08-05T14:01:36.843 回答
3

您的 LINQ group by 查询获取原始列表,对其执行附加分组,然后根据该分组修剪列表。

考虑一个列表包含这些项目的情况:

GroupID GroupFin ZipCode Name
------- -------- ------- ----
      1        1   94111    A
      1        1   94111    B
      1        1   94111    C
      1        1   94111    D
      1        2   94110    E
      1        2   94110    F

Group by 将从这六个列表中组成两个组:

GroupID=1 GroupFin=1 ZipCode=94111
GroupID=1 GroupFin=2 ZipCode=94110

第一组将包含提供者 A、B、C 和 D;第二组将包含 E 和 F。

您的查询所做的下一件事是应用First. 此操作从组中选择初始项目;在这种情况下,它将是 A 和 E。其余项目被忽略。

于 2014-08-05T14:09:10.050 回答