如何增强我的以下功能
personList.Sort (delegate (Person firstPerson, Person secondPerson) {
return firstPerson.Lastname.CompareTo (secondPerson.Lastname);
});
首先在姓氏之后排序,而不是在名字之后?
答案 0 :(得分:5)
您可以检查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();
答案 1 :(得分:2)
非常简单:
var result = firstPerson.Lastname.CompareTo(secondPerson.Lastname);
return result != 0 ? result : firstPerson.Firstname.CompareTo(secondPerson.Firstname);
答案 2 :(得分:1)
使用LINQ(仅在您可以/想要重新分配personList
时才有用):
personList = personList
.OrderBy(x => x.Lastname)
.ThenBy(x => x.Firstname)
.ToList();