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?
Thanks to everyone who helped. As it turns out, the issue was that in the original class, the hour was are nullable, like so:
The real class I’m using is a generated class that is much larger than the example I gave here – I tried to shorten it up to clarify things, and ended up leaving out the relevant part.
Changing the sort to use the value of the nullable int works:
The error message wasn’t much help there, but everyone’s working examples allowed me to track it down.