且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在一个列表中排序个月

更新时间:2023-11-23 19:43:10

您可以解析字符串转换成的DateTime ,然后使用排序月份整数属性。看到这里支持的月份名称:的http:// MSDN。 microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx



事情是这样的:

  VAR sortedMonths = monthList 
。选择(X =>新建{名称= X,排序= DateTime.ParseExact(X,MMMM的CultureInfo .InvariantCulture)})
.OrderBy(X => x.Sort.Month)
。选择(X => x.Name)
.ToArray();


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

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