C# 按属性值对对象列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16620135/
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
Sort a list of objects by the value of a property
提问by Joe
I have a list of cities.
我有一个城市列表。
List<City> cities;
I'd like to sort the list by population. The code I'm imagining is something like:
我想按人口对名单进行排序。我想象的代码是这样的:
cities.Sort(x => x.population);
but this doesn't work. How should I be sorting this list?
但这不起作用。我应该如何对这个列表进行排序?
采纳答案by David
Use OrderBy of Linq function. See http://msdn.microsoft.com/en-us/library/bb534966.aspx
使用 Linq 函数的 OrderBy。请参阅http://msdn.microsoft.com/en-us/library/bb534966.aspx
cities.OrderBy(x => x.population);
回答by Rajasekar Gunasekaran
Use this ,this will work.
使用这个,这将起作用。
List<cities> newList = cities.OrderBy(o=>o.population).ToList();
回答by Wyatt Earp
As another option, if you aren't fortunate enough to be able to use Linq, you can use the IComparer or IComparable interface.
作为另一种选择,如果您不够幸运无法使用 Linq,则可以使用 IComparer 或 IComparable 接口。
Here is a good KB article on the two interfaces: http://support.microsoft.com/kb/320727
这是关于这两个接口的一篇很好的知识库文章:http: //support.microsoft.com/kb/320727
回答by WaughWaugh
You can do this without LINQ. See the IComparable interface documentation here
您可以在没有 LINQ 的情况下执行此操作。请参阅此处的 IComparable 接口文档
cities.Sort((x,y) => x.Population - y.Population)
Or you can put this Comparison function within the City class,
或者你可以把这个比较函数放在 City 类中,
public class City : IComparable<City>
{
public int Population {get;set;}
public int CompareTo(City other)
{
return Population - other.Population;
}
...
}
Then you can just do,
那你就可以做,
cities.Sort()
And it will return you the list sorted by population.
它会返回按人口排序的列表。

