2013-04-02 113 views
2

我有以下列表:C#排序自定義列表

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

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

,我想要做的是什麼樣這份名單由郊區,然後街。 我已經看到了,我可以通過屬性(郊區在這種情況下)的一個排序:

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

,但我想通過郊區進行排序,然後街。 由於

回答

8

可以通過使用ThenBy(或ThenByDescending)鏈進一步排序調用:

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

您也可以使用Comparison委託這樣的:

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

然後:

List<Address> MyAddressList = new List<Address>(); 
MyAddressList.Sort(CompareAddress);