Sorting months in a list

后端 未结 8 2041
闹比i
闹比i 2020-12-19 10:00

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 search

8条回答
  •  执笔经年
    2020-12-19 10:28

    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();
    

提交回复
热议问题