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()
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
C# has a built-in Sort() method that performs in-place sorting to sort a list of objects. The sorting can be done using a Comparison<T> delegate or an IComparer<T> implementation.
Sorting in C# In C#, we can do sorting using the built-in Sort / OrderBy methods with the Comparison delegate, the IComparer , and IComparable interfaces.
Maybe something like this:
List<Leg> legs = GetLegs()
.OrderBy(o=>o.Day)
.ThenBy(o=>o.Hour)
.ThenBy(o=>o.Min).ToList();
You can write a custom IComparer<Leg>
and pass it to the List<T>.Sort
method.
Alternatively, you can implement IComparable<Leg>
in your class and simply call List<T>.Sort
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With