【问题标题】:How to sort class list by integer property? [duplicate]如何按整数属性对类列表进行排序? [复制]
【发布时间】:2015-08-24 21:03:27
【问题描述】:

下面我创建了一个包含 4 个 Person 类型元素的列表。我想根据 Age 属性按升序对 Person 列表进行排序。有没有一种优雅的方法可以使用 LINQ 或 IComparable(或其他东西)来实现这一点,这样我就不必从头开始编写自己的算法了?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> people = new List<Person>();
            people.Add(new Person("Matthew", 27));
            people.Add(new Person("Mark", 19));
            people.Add(new Person("Luke", 30));
            people.Add(new Person("John", 20));

            // How to sort list by age?

        }

        private class Person
        {
            string Name { get; set; }
            int Age { get; set; }

            public Person(string name, int age)
            {
                Name = name;
                Age = age;
            }
        }
    }
}

【问题讨论】:

  • 啊,必须的,“让我们对你投反对票,因为你不知道用什么确切的关键字来搜索以找到重复的问题”...
  • 重复警察又钉了一个... :)

标签: c# linq sorting


【解决方案1】:

试试这个:

List<Person> SortedList = people.OrderBy(o => o.Age).ToList();

【讨论】:

    【解决方案2】:
    people.Sort((p1, p2) =>
    {
      return p1.Age - p2.Age;
    });
    

    【讨论】:

    • Linq 已经在 OrderBy() 中带有完全相同的代码
    • 是的,我说得太早了,我一开始还以为你有一个比较。所以你是对的,它不存在,但是 int 已经实现了 IComparable ,所以 IMO 只使用内置的 OrderBy 是最“优雅的方式来完成这个”
    • OrderBy 不会对列表进行就地排序。您可以将它与.ToList() 结合起来创建一个新的排序列表,但它不会对原始列表进行排序,就像这个解决方案一样。
    • 我不太明白它是如何工作的,但这是我可以获得一个列表以在整数字段上排序的唯一方法。 .OrderBy 不适用于整数值。
    猜你喜欢
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2010-10-26
    • 2015-09-21
    • 1970-01-01
    • 2011-02-01
    • 2012-08-05
    • 2015-08-18
    相关资源
    最近更新 更多