linq order by Month Name and Year (MMM yyyy string)

asp.net, c#, linq

Solution

It's sorting alphabetically because `wkdate` is a `String` value and not a `DateTime`. You need to parse it first:

var monthlist = monthlist1.Union(monthlist2)
    .Distinct()
    // monthname is a String in format MMM yyyy
    .OrderBy(m => DateTime.Parse(m.monthname))
    .ToList();

I'm assuming that since your current `wkdate` values follow a format of `MMM yyyy` (e.g. `Apr 2012`) they will all parse properly. This is a bold assumption, I know.

You will also have to format the values back into a `String` representation for your final result.

Problem

How can i order by the month name and year in linq, it currently orders alphabetically and that is causing an issue when the report is displayed I am looking for Nov 2011, Dec 2011, Jan 2012, Feb 2012 my main concern is with result MonthList as it is the union between monthlist1 and monthlist2 Thanks for the help and insight ``` var monthlist1 = data. Select(x => new { wkdate = x.WKENDDATE }). OrderBy(y => y.wkdate). Select(m => new { monthname = m.wkdate.ToString("MMM yyyy", CultureInfo.CreateSpecificCulture("en-US")) }). Distinct(). ToList(); var monthlist2 = data.Select(x => new { wkdate = ExportHelper.getSplitEndDate(x.WKENDDATE).AddDays(1)}) .OrderBy(y => y.wkdate) .Where(l => ExportHelper.isSplitWeek(l.wkdate.AddDays(-6), l.wkdate) == true) .Select(m => new { monthname = m.wkdate.ToString("MMM yyyy", CultureInfo.CreateSpecificCulture("en-US")) }) .Distinct() .ToList(); var monthlist = monthlist1. Union(monthlist2). Distinct(). OrderBy(m=> m.monthname). ToList(); ```

Original source