Search code examples
c#sortingcompareto

Sort list after lastname and than after firstname in C#


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?


Solution

  • 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();