I have seen previous questions which are related my query but couldn't figure out on how to resolve my issue.
I have a list "Sites" with one of the items as "Year". It is defined as string and is in the format "MM/yyyy". When I try to sort the list based on the year, I'm facing a small problem.
Data for "Year" is
01/2012
04/2012
01/2013
06/2012
When I sort the list by using orderby, the output I'm getting is
01/2012
01/2013
04/2012
06/2012
which is incorrect.
Cannot convert the string using Convert.ToDateTime
as the string format doesn't contain day value. How should I go forward with this? How to implement DateTime.TryParseExact
without changing the format of the string?
Note : The format should be the same and the list should be sorted.
you could try something like this without having to change the input this will give you the order that you like also look at the OrderByDescending
property if you need it in a different sort order
var dateList = new List<string> { "01/2012", "04/2012", "01/2013", "06/2012" };
var orderedList = dateList.OrderBy(x => DateTime.Parse(x)).ToList();
You can still convert the string to a date within a LINQ statement, and the items will stay as strings.
var strings = new[]
{
"01/2012",
"04/2012",
"01/2013",
"06/2012"
};
var ordered = strings.OrderBy(s =>
{
var split = s.Split('/');
return new DateTime(int.Parse(split[1]), int.Parse(split[0]), 1);
});
Your last item will then be "01/2013"
.
As MethodMan showed in his answer, DateTime.Parse()
will be able to parse a MM/yyyy
formatted dated. However, if you need to perform anything that takes more than one line, this would be how you can do that. NB: This will not work in any query against a DbContext!
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