LINQ group by and order by in C #

I need to convert my list of cities into a group by state and sort by city within it.

I tried below one, but could not get it right. Would appreciate any help with this.

cities.GroupBy(g => g.state).Select(o => o.OrderBy(c => c.cityname)); 
+4
source share
4 answers

Try entering the code

 cities.GroupBy(g => g.state) .Select(o =>new { State = o.Key, Cities = o.OrderBy(c => c.cityname).Tolist()}) .Tolist(); 
+9
source
 cits.OrderBy(d => d.cityname).GroupBy(d => d.state).SelectMany(g => g).ToList(); 

1 - first order cityname .

2 - Then group them according to state . Since you order first, the groups are still ordered by the cityname property.

3 - Convert to one list. Otherwise, you will get a list of groups.

Must work. I also recommend using a camel note to indicate your variables.

+3
source

First do the order:

 cities.OrderBy(c=>c.cityname).GroupBy (c => c.state); 

You may need to arrange the states.

 cities.OrderBy(c=>c.cityname).GroupBy (c => c.state).OrderBy (g => g.Key); 
+2
source

The ToLookup function can give you what you need.

 cities.ToLookup(c => c.state, c => c.city); 

This will create IGrouping<string, string> where you can iterate through the Key values ​​(states) and work with a set of city values.

To sort it first, just do cities.OrderBy(c => c.state).ThenBy(c => c.city) .

+2
source

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


All Articles