Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# lists - sorting date problem

Tags:

date

c#

sorting

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

like image 281
jumbojs Avatar asked Jul 04 '26 11:07

jumbojs


2 Answers

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)));
like image 99
Chris Hynes Avatar answered Jul 07 '26 02:07

Chris Hynes


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.

like image 20
Joel Coehoorn Avatar answered Jul 07 '26 01:07

Joel Coehoorn