我有以下列表:
public class Address{
public string Number { get; set; }
public string Street { get; set; }
public string Suburb { get; set; }
}
List<Address> MyAddressList = new List<Address>();
我想要做的是按郊区和街道对此列表进行排序。 我已经看到我可以按其中一个属性(本例中为Suburb)排序:
MyAddressList = MyAddressList.OrderBy( x => x.Suburb ).ToList();
但我想按郊区然后街道排序。 感谢
答案 0 :(得分:8)
您可以使用ThenBy(或ThenByDescending)调用链接进一步排序:
MyAddressList = MyAddressList.OrderBy( x => x.Suburb ).ThenBy(x => x.Street).ToList();
答案 1 :(得分: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();
如果需要,您还可以chain multiple ThenBy。
答案 2 :(得分: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);