Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphabetically sort a generic list of objects using a specified property

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?

like image 292
Jammerz858 Avatar asked Dec 09 '22 01:12

Jammerz858


1 Answers

Assuming:

 List<Person> personList;

then with Linq:

 IEnumerable<Person> orderedByLastName = personList.OrderBy(p => p.LastName)
like image 193
spender Avatar answered Dec 11 '22 14:12

spender