I have a C# list collection that I'm trying to sort. The strings that I'm trying to sort are dates "10/19/2009","10/20/2009"...etc. The sort method on my list will sort the dates but the problem is when a day has one digit, like "10/2/2009". When this happens the order is off. It will go "10/19/2009","10/20/2009","11/10/2009","11/2/2009","11/21/2009"..etc. This is ordering them wrong because it sees the two as greater than the 1 in 10. How can I correct this?
thanks
The problem is they're strings, but you want to sort them by dates. Use a comparison function that converts them to dates before comparing. Something like this:
List<string> strings = new List<string>();
// TODO: fill the list
strings.Sort((x, y) => DateTime.Parse(x).CompareTo(DateTime.Parse(y)));
Assuming all your strings will parse:
MyList.OrderBy(d => DateTime.Parse(d));
Otherwise, you might need to use ParseExact() or something a little more complicated.
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