31

我有一个城市列表。

 List<City> cities;

我想按人口对列表进行排序。我想象的代码是这样的:

 cities.Sort(x => x.population);

但这不起作用。我应该如何排序这个列表?

4

4 回答 4

56

使用 Linq 函数的 OrderBy。请参阅http://msdn.microsoft.com/en-us/library/bb534966.aspx

cities.OrderBy(x => x.population);
于 2013-05-18T02:39:26.703 回答
19

使用这个,这将工作。

List<cities> newList = cities.OrderBy(o=>o.population).ToList();
于 2013-05-18T02:43:51.743 回答
5

您可以在没有 LINQ 的情况下执行此操作。请参阅此处的 IComparable 接口文档

cities.Sort((x,y) => x.Population - y.Population)

或者您可以将此比较函数放在 City 类中,

public class City : IComparable<City> 
{
    public int Population {get;set;}

    public int CompareTo(City other)
    {
        return Population - other.Population;
    }
 ...
}

然后你可以这样做,

cities.Sort()

它会返回按人口排序的列表。

于 2018-05-31T08:19:23.087 回答
2

作为另一种选择,如果您不够幸运无法使用 Linq,则可以使用 IComparer 或 IComparable 接口。

这是关于这两个接口的一篇很好的知识库文章:http: //support.microsoft.com/kb/320727

于 2013-05-18T04:18:05.570 回答