下面我创建了一个包含 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)
尝试这个:
List<Person> SortedList = people.OrderBy(o => o.Age).ToList();
Run Code Online (Sandbox Code Playgroud)
people.Sort((p1, p2) =>
{
return p1.Age - p2.Age;
});
Run Code Online (Sandbox Code Playgroud)