Sort string list with dates in C#
With linq:
var list = new List<string> {"01/01/2013", "10/01/2013", "20/01/2013"};
var orderedList = list.OrderByDescending(x => DateTime.Parse(x)).ToList();
UPDATE (according questions in comments):
You can treat invalid dates like this (invalid date is there treated as default(DateTime)
):
var list = new List<string> { "01/01/2013", "10/01/2013", "N/A" , "20/01/2013" };
var orderedList2 = list.OrderByDescending(x =>
{
DateTime dt;
DateTime.TryParse(x, out dt);
return dt;
});
Or if you want to have invalid datetime as first item in the list:
var orderedList3 = list.OrderByDescending(x =>
{
DateTime dt;
if (!DateTime.TryParse(x, out dt)) return DateTime.MaxValue;
return dt;
});
You can also filter the invalid dates out:
var filteredList = list.Where(x =>
{
DateTime dt;
return DateTime.TryParse(x, out dt);
}).Select(DateTime.Parse).OrderByDescending(x => x);
Or even better:
var filteredList = list.Select(x =>
{
DateTime dt;
return new {valid = DateTime.TryParse(x, out dt), date = dt};
}).Where(x => x.valid).Select(x => x.date).OrderByDescending(x => x);
You shouldn't use string representations of data - we're all living in object-oriented world :)
Best way would be to convert these strings into actual DateTime objects and sort them in reverse order via linq:
var dates = Array.ConvertAll(dateStrings, x => DateTime.Parse(x));
return dates.OrderByDesc(x => x);
Another way would be to implement custom sorting function, see this link. Then you'd just use it in a sort function:
DateAsStringComparer myComparer = new DateAsStringComparer();
dateStrings.Sort(myComparer);
Try this:
List<string> s = new List<string>() { "01/01/2013", "10/01/2013", "20/01/2013" };
var d = s.OrderByDescending(i => DateTime.ParseExact(i, "dd/MM/yyyy", null));