📅  最后修改于: 2023-12-03 15:17:19.785000             🧑  作者: Mango
在LINQ中,使用ThenBy方法可以对已经排序的集合再次排序,以便达到多级排序的目的。
ThenBy方法跟在OrderBy或OrderByDescending方法的后面,用于对前一个排序条件的结果再次排序。
var result = from student in students
orderby student.LastName, student.FirstName
select student;
在上面的代码中,OrderBy方法先对LastName进行字母升序排序,如果LastName相同,则对FirstName再进行排序。但我们也可以将第二个排序条件改为ThenBy方法:
var result = from student in students
orderby student.LastName, student.FirstName
select student;
// 使用ThenBy方法进行多级排序
var result2 = from student in students
orderby student.LastName
select student;
result2 = result2.ThenBy(student => student.FirstName);
如上代码所示,我们将LastName作为第一排序条件,通过OrderBy方法进行排序;接着使用ThenBy方法对FirstName再次排序。 这个按Last Name排序的示例也可用Lambda表达式来写:
var result = students.OrderBy(student => student.LastName)
.ThenBy(student => student.FirstName);
如果我们需要按照不同类型的顺序进行排序的话,可以使用泛型IComparer接口来完成。例如,我们将根据以下字段进行排序:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class PersonComparer : IComparer<Person>
{
public int Compare(Person x, Person y)
{
//按照Name属性进行排序
int value = string.Compare(x.Name, y.Name, true);
if (value == 0)
{
//如果Name相同,则按照Age属性进行排序
value = x.Age.CompareTo(y.Age);
if (value == 0)
{
//如果Age相同,则按照DateOfBirth属性进行排序
value = x.DateOfBirth.CompareTo(y.DateOfBirth);
}
}
return value;
}
}
然后就可以使用PersonComparer类来对Person对象进行排序了。
var people = new List<Person>() {
new Person() { Name = "Tom", Age = 23, DateOfBirth = new DateTime(1998, 3, 12) },
new Person() { Name = "Mary", Age = 23, DateOfBirth = new DateTime(1998, 5, 6) },
new Person() { Name = "John", Age = 22, DateOfBirth = new DateTime(1999, 11, 8) },
new Person() { Name = "Alice", Age = 22, DateOfBirth = new DateTime(1999, 1, 2) }
};
var sortedList = people.OrderBy(p => p, new PersonComparer());