C # Explanation of lambda expression

I found this lambda expression:

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

Correct me if I'm wrong, but with this lambda you can distinguish myCustomerList from CustomerId and what I need. But I'm trying to figure out how this works.

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

The second choice is happening, and this is the part that I do not get. The choice selects the client, but how can he choose the client from the dictionary? You need a key for this, because of the group. Where is this key? And how does First() help here?

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

+4
source share
2 answers

He does not select it from the dictionary - he says for each group as a result of GroupBy , select the first entry. Note that IGrouping<TKey, TElement> implements IEnumerable<TElement> .

Basically, a group has two things:

  • Key
  • List of items

This is the selection of the first item from each group.

+4
source

Lets say your collection:

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

After the band becomes

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

After the last selection (select the first of the values ​​in the above notation:

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

Therefore, it is a great client based on ID.

+3
source

All Articles