【问题标题】:Sort a list of objects by the value of a property [duplicate]按属性值对对象列表进行排序[重复]
【发布时间】:2013-05-18 02:34:26
【问题描述】:

我有一个城市列表。

 List<City> cities;

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

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

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

【问题讨论】:

  • 乔,你必须有两个参数。一个是项目,另一个是比较器。检查我链接的帖子中的示例
  • 让我看看我是否做对了。 Sort 函数只接受一个参数,它是一个 lambda/delegate,它接受 两个 参数并且应该像 运算符一样工作?

标签: c#


【解决方案1】:

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

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

【讨论】:

  • 需要注意的是,unline Sort, OrderBy 不会修改输入。
  • 或者如果你想简单的把列表倒序输出,可以使用cities.Reverse()
  • 或者:OrderByDescending
【解决方案2】:

用这个就行了。

List<cities> newList = cities.OrderBy(o=>o.population).ToList();

【讨论】:

    【解决方案3】:

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

    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()
    

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2010-10-26
        • 1970-01-01
        • 2011-10-11
        • 2014-08-25
        • 1970-01-01
        • 2015-09-21
        • 2013-02-12
        • 2023-04-03
        • 2016-11-25
        相关资源
        最近更新 更多