4

我需要将我的城市列表按州分组并按城市排序。

我尝试了以下一项,但无法正确处理。将不胜感激任何帮助。

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

4 回答 4

10

试试下面的代码

cities.GroupBy(g => g.state)
.Select(o =>new { 
          State = o.Key,
         Cities = o.OrderBy(c => c.cityname).Tolist()})
.Tolist();
于 2013-05-10T10:37:53.150 回答
3

The ToLookup function may give you what you need.

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

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

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

于 2013-05-10T10:50:26.667 回答
3
cits.OrderBy(d => d.cityname).GroupBy(d => d.state).SelectMany(g => g).ToList();

1 -cityname先排序。

2 - 然后根据 对它们进行分组state。由于您首先订购,因此仍然根据cityname属性对组进行订购。

3 - 转换为单个列表。否则,您将得到组列表。

应该管用。我还建议使用骆驼大小写表示法来命名变量。

于 2013-05-10T10:42:08.807 回答
2

先做orderby:

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

您可能想要命令各州这样做。

cities.OrderBy(c=>c.cityname).GroupBy (c => c.state).OrderBy (g => g.Key);
于 2013-05-10T10:41:25.227 回答