LINQ groupby question

I have a collection called navigationList . This list contains customer objects. The client has the Town property.

The list contains 5 customers: 2 with the city of New York and 5 with the city of Madrid.

I want the list to have only 2 clients. 1 with the city of New York and one with Madrid. If 2 is from New York, I want the latter. The same goes for Madrid.

What will the LINQ statement look like?

 var newList = navigationList.GroupBy(c => c.Town) // ? 
+6
source share
1 answer

You need something like

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

However, first you want OrderBy so that Last makes sense:

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

In this case, the order is executed using the customer ID.

+18
source

Source: https://habr.com/ru/post/894021/


All Articles