Martijn
Martijn

Reputation: 24789

C# Explanation about a lambda expression

I just found this lambda expression:

myCustomerList.GroupBy(cust => cust.CustomerId).Select(grp => grp.First());

Correct me if I am wrong, but with this lambda you can distinct the myCustomerList on the CustomerId and that's exaclty what I need. But I am trying to figure out how it works.

The first step is the groupby: this result in a dictionary, IGouping<long, Customer> with the CustomerId as the key of the dictionary.

Second a select takes place and this is the part I don't get. The select selects a customer, but how can it select a Customer from a dictionary? You need a key for this, because of the group by. Where's that key? And how is First() helping here?

Can you tell me in detail how the last part works?

Upvotes: 4

Views: 253

Answers (2)

Ankur
Ankur

Reputation: 33637

Lets says your collection is:

{Name=a, CustomerId=1}
{Name=a, CustomerId=1}
{Name=b, CustomerId=2}
{Name=b, CustomerId=2}

After group by it becomes

{ key = 1, Values = {Name=a, CustomerId=1}, {Name=a, CustomerId=1} }
{ key = 2, Values = {Name=a, CustomerId=2}, {Name=a, CustomerId=2} }

After last select (i.e select first from the Values in the above notation it becomes:

{Name=a, CustomerId=1}
{Name=a, CustomerId=2}

Hence it is distinct customer based on the ID.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500515

It's not selecting it from the dictionary - it's saying for each grouping in the result of GroupBy, select the first entry. Note that IGrouping<TKey, TElement> implements IEnumerable<TElement>.

Basically a group has two things:

  • A key
  • A list of elements

This is selecting the first element from each group.

Upvotes: 4

Related Questions