按属性值对对象列表进行排序

Joe*_*Joe 23 c#

我有一份城市名单.

 List<City> cities;
Run Code Online (Sandbox Code Playgroud)

我想按人口排序.我想象的代码是这样的:

 cities.Sort(x => x.population);
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我应该如何排序这个清单?

Dav*_*vid 47

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

cities.OrderBy(x => x.population);
Run Code Online (Sandbox Code Playgroud)

  • 重要的是要注意unline Sort,OrderBy不会修改输入. (17认同)

Raj*_*ran 17

使用它,这将工作.

List<cities> newList = cities.OrderBy(o=>o.population).ToList();
Run Code Online (Sandbox Code Playgroud)


Wau*_*ugh 5

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

cities.Sort((x,y) => x.Population - y.Population)
Run Code Online (Sandbox Code Playgroud)

或者你可以把这个比较函数放在 City 类中,

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

    public int CompareTo(City other)
    {
        return Population - other.Population;
    }
 ...
}
Run Code Online (Sandbox Code Playgroud)

那你就可以做,

cities.Sort()
Run Code Online (Sandbox Code Playgroud)

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