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

3 Answers 3

8

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

MyAddressList = MyAddressList.OrderBy( x => x.Suburb ).ThenBy(x => x.Street).ToList();
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.