I'm new to lambda expressions, and just ran into something I don't understand.
I have an object like so:
class MyListItem
{
string date; //date in the format "2010-12-05"
int Hour; //hour of day as an int
}
I have a list of these objects, representing some dates and hours.
I want to sort this list by date and hour, so I try this:
List<MyListItem> myList = new List<MyListItem>();
myList = getsomedata(); //populate list
myList.Sort((a, b) => (a.date + a.Hour.ToString()).CompareTo(b.date + b.Hour.ToString()));
and that works, sort of. The issues is that the hour is an int, so it's sometimes not 2 digits, resulting in a sort like so:
2010-12-05 1
2010-12-05 10
2010-12-05 11
2010-12-05 12
2010-12-05 13
2010-12-05 2
2010-12-05 21
2010-12-05 22
I want it to be like:
2010-12-05 1
2010-12-05 2
2010-12-05 10
2010-12-05 11
2010-12-05 12
2010-12-05 13
2010-12-05 21
2010-12-05 22
so I try formatting the string to add a zero before I parse together in the lambda:
ret.Sort((a, b) => (a.date + a.Hour.ToString("00")).CompareTo(b.date + b.Hour.ToString("00")));
But it won't compile. It tells me:
Cannot convert lambda expression to type 'Systems.Collections.Generic.IComparer<MyListItem>' because it is not a delegate type.
Huh? What is different between the plain .ToString() (with no format string) and .ToString("00") in this situation?
Also, any suggestions as to how to get this working?
I'm not at a PC so I can't explain the first, but I'd sidestep it:
ret.Sort((a,b) => {
int result = string.Compare(a.date,b.date);
if(result==0) result = a.hour.CompareTo(b.hour);
return result;
});
Less string creations, no parsing overheads, etc ;)
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