testing
testing

Reputation: 20279

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?

Upvotes: 0

Views: 3928

Answers (3)

knittl
knittl

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

Selman Genç
Selman Genç

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

user2160375
user2160375

Reputation:

It's pretty simple:

var result = firstPerson.Lastname.CompareTo(secondPerson.Lastname);
return result != 0 ? result : firstPerson.Firstname.CompareTo(secondPerson.Firstname);

Upvotes: 2

Related Questions