在C#中,将列表排序在姓氏之后,而不是在姓氏之后
本文关键字:之后 排序 列表 | 更新日期: 2023-09-27 18:20:57
我如何增强以下功能
personList.Sort (delegate (Person firstPerson, Person secondPerson) {
return firstPerson.Lastname.CompareTo (secondPerson.Lastname);
});
先排序在姓后,然后排序在名后?
您可以检查Lastnames
是否相等,并进行相应的比较:
personList.Sort (delegate (Person firstPerson, Person secondPerson)
{
if(firstPerson.Lastname == secondPersonLasname)
return firstPerson.Firstname.CompareTo(secondPerson.Firstname);
return firstPerson.Lastname.CompareTo (secondPerson.Lastname);
});
如果你想使用Linq,还有另一种方法:
personList = personList.OrderBy(p => p.LastName).ThenBy(p => p.Firstname).ToList();
很简单:
var result = firstPerson.Lastname.CompareTo(secondPerson.Lastname);
return result != 0 ? result : firstPerson.Firstname.CompareTo(secondPerson.Firstname);
使用LINQ(仅在您可以/想要重新分配personList
时有用):
personList = personList
.OrderBy(x => x.Lastname)
.ThenBy(x => x.Firstname)
.ToList();