Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting months in a list

Tags:

c#

I have a list of strings which contains months of the year. I need to be able to sort this list so the months are in order by month, not alphabetically. I have been searching for awhile but I can't see to wrap my head around any of the solutions I've found.

Here's an example of how the months might be added. They are added dynamically based off of fields in a SharePoint list so they can be in any order and can have duplicates (I am removing these with Distinct()).

List<string> monthList = new List<string>();
monthList.Add("June");
monthList.Add("February");
monthList.Add("August");

Would like to reorder this to:

February
June
August
like image 349
Mike Avatar asked Dec 16 '11 19:12

Mike


2 Answers

You could parse the string into a DateTime and then sort using the month integer property. See here for supported month names: http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx

Something like this:

var sortedMonths = monthList
    .Select(x => new { Name = x, Sort = DateTime.ParseExact(x, "MMMM", CultureInfo.InvariantCulture) })
    .OrderBy(x => x.Sort.Month)
    .Select(x => x.Name)
    .ToArray();
like image 138
lbergnehr Avatar answered Oct 24 '22 17:10

lbergnehr


You can parse month names into dates (it assumes the current year and day 1):

monthList = monthList.OrderBy(s=> DateTime.ParseExact(s, "MMMM", new CultureInfo("en-US"))).ToList();
like image 25
D Stanley Avatar answered Oct 24 '22 17:10

D Stanley