Reputation: 3661
I have a date field for which I convert the value of the database from datetime to string format("dd-MMM-yyyy"), I need to perform sorting this string date field, but seems like when I have been doing the sorting, it is working and checking only the date, not the month as well as not the year. So when the data is in date format (database):
2012-01-29
2011-01-01
2013-03-28
So it is sorted like
2013-03-28
2012-01-29
2011-01-01
But it is sorted: 29-Jan-2012 28-Mar-2013 01-Jan-2011
So I want to apply orderbydescending-> then by-> so on, I need to split the string from end, is there a way around? I am doing:
List<c> lst=lst.OrderByDescending(d=>d.TDate.Substring(d.TDate.LastIndexOf('-').toList();
Upvotes: 0
Views: 1333
Reputation: 24302
How about this,
List<string> lst= new List<string>{"29-Jan-2012", "28-Mar-2013", "01-Jan-2011","2011-01-01","2013-03-28"};
lst.OrderByDescending(x=>DateTime.Parse(x));
in your sample it should be,
lst.OrderByDescending(x=>DateTime.Parse(x.TDate))
Upvotes: 1
Reputation: 460028
If you want to order a string like a date, parse it to DateTime
:
List<c> lst = lst
.Select(x => new { Obj = x, Date = DateTime.Parse(x.TDate) })
.OrderByDescending(x => x.Date)
.Select(x => x.Obj).ToList();
Even better, store a DateTime
in the first place and convert it to a string at the very last place.
Upvotes: 0
Reputation: 333
Things are easier when you use dates. First I'd look at getting dates out of the database without converting to a string. If that fails you can do this...
lst.OrderByDescending(d=>DateTime.Parse(d.TDate))
Upvotes: 0