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?
You can use an implementation of
IComparer<T>:You would use it in the
Sortmethod of yourAddressBookclass like this, assumingPeopleis aList<Person>:This code has the benefit of using an in-place sort.