Reputation: 20279
How can I enhance my following function
personList.Sort (delegate (Person firstPerson, Person secondPerson) {
return firstPerson.Lastname.CompareTo (secondPerson.Lastname);
});
to first sort after last name and than after first name?
Upvotes: 0
Views: 3928
Reputation: 265271
With LINQ (only useful, if you can/want to re-assign personList
):
personList = personList
.OrderBy(x => x.Lastname)
.ThenBy(x => x.Firstname)
.ToList();
Upvotes: 1
Reputation: 101701
You can check if Lastnames
are equal and do the comparison accordingly:
personList.Sort (delegate (Person firstPerson, Person secondPerson)
{
if(firstPerson.Lastname == secondPersonLasname)
return firstPerson.Firstname.CompareTo(secondPerson.Firstname);
return firstPerson.Lastname.CompareTo (secondPerson.Lastname);
});
If you would like to use Linq there is also another way:
personList = personList.OrderBy(p => p.LastName).ThenBy(p => p.Firstname).ToList();
Upvotes: 6
Reputation:
It's pretty simple:
var result = firstPerson.Lastname.CompareTo(secondPerson.Lastname);
return result != 0 ? result : firstPerson.Firstname.CompareTo(secondPerson.Firstname);
Upvotes: 2