I can’t figure out how to do this, these two questions aren’t working for me. One says I can’t use the delegate and the comparer, and the other says that it can’t convert the lambda to a delegate.
I have a GenericList<T> of ScheduleItem. Each item has a PaymentDate property which is a DateTime?.
I basically want to sort this list on that property (old->newest). What’s the easiest way to do this?
First I tried this:
transaction.ScheduleCollection.Sort(delegate(ScheduleItem p1, ScheduleItem p2)
{
return p1.PaymentDate.CompareTo(p2.PaymentDate);
});
And I get these two errors:
Cannot convert anonymous method to type ‘System.Collections.IComparer’
because it is not a delegate type‘System.Nullable’ does not contain a definition for
‘CompareTo’ and no extension method ‘CompareTo’ accepting a first
argument of type ‘System.Nullable’ could be found
(are you missing a using directive or an assembly reference?)
And the other one I tried was this:
transaction.ScheduleCollection.Sort((lhs, rhs) => (lhs.PaymentDate.CompareTo(rhs.PaymentDate)));
and get
Cannot convert anonymous method to type ‘System.Collections.IComparer’
because it is not a delegate type
public void Sort(IComparer comparer);
That’s the sort method I have to work with.
Have you thought about using LINQ?
Something like:
var list = list.OrderBy(x => x.PaymentDate).ToList();