SSC
SSC

Reputation: 311

How to Sort a List by a property in the object

I have a class called Factor which has properties as Id,Explain,Date,Amount and .... I have a List of this "Factor " class.

Now i want to sort the list based on one property of the Factor object(by date)

public class Factor
    {
        public DateTime? date { set; get; }
        public string InnovoiceId { set; get; }
        public string explain { set; get; }
        public Int64? bedehkar { set; get; }
        public Int64? bestankar { set; get; }
        public Int64? mande { set; get; }



     }

        List<Factor> factors=new List<Factor>();

How can i do this in C# ?

Upvotes: 2

Views: 5043

Answers (2)

O. R. Mapper
O. R. Mapper

Reputation: 20710

You can use one of the overloads of the Sort method. A simply one to use is this one that takes a lambda expression for the sorting criterion - essentially a function that takes two elements and returns a comparison result:

factors.Sort((x, y) => x.date.CompareTo(y.date));

As you are using DateTime?, you also need to check whether there is currently a value stored in there.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

You can use LINQ to get new list with items sorted:

var sortedFactors = factors.OrderBy(x => x.explain).ToList();

or you can sort it in-place using List<T>.Sort method:

factors.Sort((e1, e2) => e1.explain.CompareTo(e2.explain));

Update

Using List<T>.Sort with date property is a little bit more tricky, because its Nullable<DateTime>, and it's not really obvious how to order null and non-null values.

factors.Sort((e1, e2) => e1.date.HasValue ? (e2.date.HasValue ? e1.date.Value.CompareTo(e2.date.Value) : -1) : ((e2.date.HasValue ? 1 : 0)));

Upvotes: 7

Related Questions