Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of object by properties c#

Tags:

c#

list

sorting

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

like image 503
Engern Avatar asked Mar 15 '12 08:03

Engern


People also ask

How do you sort a list of objects based on an attribute of the objects in C#?

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.

Can you sort a list in C#?

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.


2 Answers

Maybe something like this:

List<Leg> legs = GetLegs()
                .OrderBy(o=>o.Day)
                .ThenBy(o=>o.Hour)
                .ThenBy(o=>o.Min).ToList();
like image 121
Arion Avatar answered Sep 23 '22 21:09

Arion


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.

like image 31
Matthias Avatar answered Sep 20 '22 21:09

Matthias