C# 中的 LINQ group by 和 order by
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16480295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ group by and order by in C#
提问by user2369630
I need to convert my city list into group by state and order by city within it.
我需要将我的城市列表按州和按城市排序。
I tried below one but not able to get it right. Would appreciate any help on this.
我试过下面一个,但没能把它做好。将不胜感激这方面的任何帮助。
cities.GroupBy(g => g.state).Select(o => o.OrderBy(c => c.cityname));
采纳答案by vijay
Try below code
试试下面的代码
cities.GroupBy(g => g.state)
.Select(o =>new {
State = o.Key,
Cities = o.OrderBy(c => c.cityname).Tolist()})
.Tolist();
回答by Bob Vale
Do the orderby first:
先做orderby:
cities.OrderBy(c=>c.cityname).GroupBy (c => c.state);
You might want to order the states to so.
您可能希望对状态进行排序。
cities.OrderBy(c=>c.cityname).GroupBy (c => c.state).OrderBy (g => g.Key);
回答by emre nevayeshirazi
cits.OrderBy(d => d.cityname).GroupBy(d => d.state).SelectMany(g => g).ToList();
1 - Order by citynamefirst.
1 - 先订购cityname。
2 - Then group them according to state. Since you order first, groups are still ordered with respect to citynameproperty.
2 - 然后根据 将它们分组state。由于您先订购,因此组仍按cityname属性排序。
3 - Convert to single list. Otherwise, you will end up with list of groups.
3 - 转换为单个列表。否则,您将得到组列表。
Should work. I also advice using camel casenotation for naming your variables.
应该管用。我还建议使用驼峰命名法来命名变量。
回答by John M Gant
The ToLookupfunction may give you what you need.
该ToLookup功能可能会为您提供所需的东西。
cities.ToLookup(c => c.state, c => c.city);
This will create an IGrouping<string, string>where you can iterate through the Keyvalues (states) and operate on a set of city values.
这将创建一个IGrouping<string, string>您可以遍历Key值(州)并对一组城市值进行操作的地方。
To sort it first, just do cities.OrderBy(c => c.state).ThenBy(c => c.city).
要先对其进行排序,只需执行cities.OrderBy(c => c.state).ThenBy(c => c.city).

