如何按整数属性对类列表进行排序?

cad*_*arp 3 c# linq sorting

下面我创建了一个包含 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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sal*_*ari 9

尝试这个:

List<Person> SortedList = people.OrderBy(o => o.Age).ToList();
Run Code Online (Sandbox Code Playgroud)


man*_*nji 7

people.Sort((p1, p2) =>
{
  return p1.Age - p2.Age;
});
Run Code Online (Sandbox Code Playgroud)

  • OrderBy 不会就地对列表进行排序。您可以将它与 `.ToList()` 结合起来创建一个新的排序列表,但它不会像这个解决方案那样对原始列表进行排序。 (3认同)