按属性c#排序对象列表
我有这堂课:
public class Leg { public int Day { get; set; } public int Hour { get; set; } public int Min { get; set; } }
我有一个获取腿列表的函数,称为GetLegs()
List legs = GetLegs();
现在我想对此列表进行排序。 所以我首先要考虑的是日,然后是小时,最后是分钟。 我该如何解决这种排序?
谢谢
也许是这样的:
List legs = GetLegs() .OrderBy(o=>o.Day) .ThenBy(o=>o.Hour) .ThenBy(o=>o.Min).ToList();
您可以编写自定义IComparer
并将其传递给List
方法。
或者,您可以在类中实现IComparable
,只需调用List
。
使用Enumerable.OrderBy方法。
我想这会有所帮助。
var o = legs.OrderBy(x => x.Day) .ThenBy(x => x.Hour) .ThenBy(x => x.Min);
您需要在类上实现IComparable
接口,以便更直观地使用C#语言对对象进行排序。 当类实现IComparable
,还必须实现public method
CompareTo(T).
Leg
类实现IComparable
,这意味着可以将Leg
实例与其他Leg
实例进行比较。
#region "Leg Class that implements IComparable interface" public class Leg:IComparable { public int Day { get; set; } public int Hour { get; set; } public int Min { get; set; } public int CompareTo(Leg leg) { if (this.Day == leg.Day) { if (this.Hour == leg.Hour) { return this.Min.CompareTo(leg.Min); } } return this.Day.CompareTo(leg.Day); } } #endregion //Main code List legs = GetLegs(); legs.Sort();