How does GroupBy in LINQ work?

ConfusedSleepyDeveloper picture ConfusedSleepyDeveloper · Aug 5, 2014 · Viewed 11.9k times · Source

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());

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?

Answer

Doctor Jones picture Doctor Jones · Aug 5, 2014

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.

If you have the following data:

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

And the following query

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

The group by will return the following results:

enter image description here

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

Which returns the following results:

enter image description here