开发者

LINQ groupby question

I have a collection called navigationList. This list holds customer objects. A customer has a property called Town.

The list holds 5 customers: 2 with town "New York", and 5 with town "M开发者_开发技巧adrid".

I want the list to only hold only 2 customers. 1 with town "New York" and one with "Madrid". If 2 are from "New York", I want the last one. Same for "Madrid".

What would the LINQ statement look like?

var newList = navigationList.GroupBy(c => c.Town) // ? 


You would want something like

var newList = navigationList.GroupBy(c => c.Town).Select(g => g.Last()).ToList();

However, you would probably want to OrderBy first, so that the Last is meaningful:

var newList = navigationList.
              GroupBy(c => c.Town).
              Select(g => g.OrderBy(c => c.Id).Last()).
              ToList();

In this case the ordering is done by customer Id.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜