开发者

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开发者_StackOverflow you tell me in detail how the last part works?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜