Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ groupby question

Tags:

c#

linq

group-by

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 "Madrid".

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) // ? 
like image 823
HerbalMart Avatar asked Aug 01 '11 10:08

HerbalMart


People also ask

How does LINQ Group by work?

GroupBy allows you to quickly group collections of related data by specific properties on your data. The grouped data is then arranged by sub-collections of items in those groups. Note: LINQ provides variants of each method in this article that work with either IEnumerable or IQueryable .

How to apply group by in C#?

The Linq GroupBy in C# belongs to the Grouping Operators category and exactly does the same thing as the Group By clause does in SQL Query. This method takes a flat sequence of elements and then organizes the elements into groups (i.e. IGrouping<TKey, TSource>) based on a given key.


1 Answers

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.

like image 113
Yakimych Avatar answered Sep 22 '22 00:09

Yakimych