Engern
Engern

Reputation: 887

Sort list of object by properties c#

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

Upvotes: 7

Views: 28263

Answers (5)

user1082916
user1082916

Reputation:

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 method CompareTo(T).

Leg class implements IComparable<Leg>, which means an Leg instance can be compared with other Leg instances.

    #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();

Upvotes: 1

Arion
Arion

Reputation: 31249

Maybe something like this:

List<Leg> legs = GetLegs()
                .OrderBy(o=>o.Day)
                .ThenBy(o=>o.Hour)
                .ThenBy(o=>o.Min).ToList();

Upvotes: 10

Sreedharlal B Naick
Sreedharlal B Naick

Reputation: 156

I guess this would help.

var o = legs.OrderBy(x => x.Day)
            .ThenBy(x => x.Hour)
            .ThenBy(x => x.Min);

Upvotes: 0

Zabavsky
Zabavsky

Reputation: 13640

Use Enumerable.OrderBy Method.

Upvotes: 0

Matthias
Matthias

Reputation: 12259

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.

Upvotes: 1

Related Questions