在列表中对月份进行排序

Mik*_*ike 5 c#

我有一个字符串列表,其中包含一年中的几个月.我需要能够对此列表进行排序,以便月份按月排序,而不是按字母顺序排列.我一直在寻找一段时间,但我无法看到我已经找到的任何解决方案.

这是一个如何添加月份的示例.它们是基于SharePoint列表中的字段动态添加的,因此它们可以按任何顺序排列,并且可以有重复项(我将使用Distinct()删除它们).

List<string> monthList = new List<string>();
monthList.Add("June");
monthList.Add("February");
monthList.Add("August");
Run Code Online (Sandbox Code Playgroud)

想将此重新排序为:

February
June
August
Run Code Online (Sandbox Code Playgroud)

lbe*_*ehr 6

您可以将字符串解析为a DateTime,然后使用month整数属性进行排序.请参阅此处获取支持的月份名称:http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx

像这样的东西:

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();
Run Code Online (Sandbox Code Playgroud)