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) // ?
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With