Alphabetically sort a generic list of objects using a specified property

Jammerz858 picture Jammerz858 · Mar 21, 2012 · Viewed 11.8k times · Source

I am writing an address book program. I have each person's details stored in a List<Person>. I need to be able to sort this list by last name (using first name if there are ties) or by post code.

So far I have this:

public class Person
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string PostCode { get; set; }
    // etc..
}

public class AddressBook
{
    public List<Person> People { get; set; }

    // asc: ascending or descending
    // column: the property to use when sorting
    //         (in my case either LastName or Postcode)
    public void Sort(bool asc, string column)
    {
        // What should I put here?
    }

    // etc...
}

I have tried using the ICompare and IComparable interfaces but I am just not getting it.

How do I write the Sort method?

Answer

Mark Byers picture Mark Byers · Mar 21, 2012

You can try using the LINQ extension methods OrderBy, OrderByDescending, ThenBy and ThenByDescending:

using System.Linq;

// ...

public void Sort(bool asc, string column)
{
    switch (column)
    {
        case "LastName":
            People = People.OrderBy(x => x.LastName).ThenBy(x => x.FirstName).ToList();
            break;
        case "PostCode":
            People = People.OrderBy(x => x.PostCode).ToList();
            break;
        default:
            // error handling
    }

    if (!asc)
    {
        People.Reverse();
    }
}

You could also look at Dynamic LINQ which would simplify this code.