2

我有以下列表:

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

但我想先按 Suburb 然后按 Street 排序。谢谢

4

3 回答 3

8

您可以使用 ThenBy(或 ThenByDescending)调用来链接进一步的排序:

MyAddressList = MyAddressList.OrderBy( x => x.Suburb ).ThenBy(x => x.Street).ToList();
于 2013-04-02T02:18:30.953 回答
4

您可以使用 ThenBy

按升序对序列中的元素进行后续排序。

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

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

如果需要,您还可以链接多个 ThenBy

于 2013-04-02T02:18:58.057 回答
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);
于 2013-04-02T02:35:22.837 回答