按属性对对象列表进行排序 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9716273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort list of object by properties c#
提问by Engern
I have this class:
我有这门课:
public class Leg
{
public int Day { get; set; }
public int Hour { get; set; }
public int Min { get; set; }
}
I have a function that gets a list of legs, called GetLegs()
我有一个获取腿列表的函数,称为 GetLegs()
List<Leg> legs = GetLegs();
Now I would like to sort this list. So I first have to consider the day, then the hour, and at last the minute. How should I solve this sorting?
现在我想对这个列表进行排序。所以我首先必须考虑一天,然后是小时,最后是分钟。我应该如何解决这个排序?
Thanks
谢谢
采纳答案by Arion
Maybe something like this:
也许是这样的:
List<Leg> legs = GetLegs()
.OrderBy(o=>o.Day)
.ThenBy(o=>o.Hour)
.ThenBy(o=>o.Min).ToList();
回答by Matthias
You can write a custom IComparer<Leg>and pass it to the List<T>.Sortmethod.
您可以编写自定义IComparer<Leg>并将其传递给List<T>.Sort方法。
Alternatively, you can implement IComparable<Leg>in your class and simply call List<T>.Sort.
或者,您可以IComparable<Leg>在您的类中实现并简单地调用List<T>.Sort.
回答by Zabavsky
Use Enumerable.OrderByMethod.
使用Enumerable.OrderBy方法。
回答by Sreedharlal B Naick
I guess this would help.
我想这会有所帮助。
var o = legs.OrderBy(x => x.Day)
.ThenBy(x => x.Hour)
.ThenBy(x => x.Min);
回答by Arion
You need to implement the IComparable<T>interface on your class to allow a more intuitive way for the objects to be sorted in the C# language. When a class implements IComparable, you must also implement the public methodCompareTo(T).
您需要IComparable<T>在您的类上实现该接口,以便以更直观的方式在 C# 语言中对对象进行排序。当一个类实现时IComparable,您还必须实现public methodCompareTo(T).
Legclass implements IComparable<Leg>, which means an Leginstance can be compared with other Leginstances.
Leg类实现IComparable<Leg>,这意味着一个Leg实例可以与其他Leg实例进行比较。
#region "Leg Class that implements IComparable interface"
public class Leg:IComparable<Leg>
{
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<Leg> legs = GetLegs();
legs.Sort();

