2

I have the following list:

public class Address{
    public string Number { get; set; }
    public string Street { get; set; }
    public string Suburb { get; set; }
}

List<Address> MyAddressList = new List<Address>();

and what I want to do is sort this list by Suburb and then Street. I have seen that I can sort by one of the properties (Suburb in this case):

MyAddressList = MyAddressList.OrderBy( x => x.Suburb ).ToList();

but I want to sort by Suburb then Street. Thanks

Michael Teper
  • 4,591
  • 2
  • 32
  • 49
Cooper Cripps
  • 205
  • 2
  • 6
  • 14

3 Answers3

8

You can chain further ordering by using ThenBy (or ThenByDescending) calls:

MyAddressList = MyAddressList.OrderBy( x => x.Suburb ).ThenBy(x => x.Street).ToList();
Khepri
  • 9,547
  • 5
  • 45
  • 61
4

You can use ThenBy

Performs a subsequent ordering of the elements in a sequence in ascending order.

http://msdn.microsoft.com/en-us/library/system.linq.queryable.thenby.aspx

MyAddressList = 
   MyAddressList.OrderBy( x => x.Suburb ).ThenBy(x => x.Street).ToList();

If needed, you can also chain multiple ThenBy.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
1

Also you can use the Comparison delegate like this:

private int CompareAddress(Address first, Address second)
{
    if (first.Suburb.Equals(second.Suburb))
    {
        return first.Street.CompareTo(second.Street);
    }
    else
    {
        return first.Suburb.CompareTo(second.Suburb);
    }
}

Then:

List<Address> MyAddressList = new List<Address>();
MyAddressList.Sort(CompareAddress);
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116