Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does GroupBy in LINQ work?

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?

like image 550
ConfusedSleepyDeveloper Avatar asked Oct 22 '25 09:10

ConfusedSleepyDeveloper


2 Answers

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

like image 194
Doctor Jones Avatar answered Oct 24 '25 21:10

Doctor Jones


What values will go in to the lists that are returned for the group?

The first for each group, because you do:

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

What happens to the rest of the values?

They will not be projected into your target dictionary.

like image 30
CodeCaster Avatar answered Oct 24 '25 21:10

CodeCaster