在一个列表中排序个月 [英] Sorting months in a list

查看:163
本文介绍了在一个列表中排序个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串列表,其中包含的一年中的月份。我需要能够使个月,以便通过一个月,不按字母顺序排序此列表。我一直在寻找一段时间,但我看不到环绕任何我已经找到了解决方案,我的头。



下面是这几个月怎么可能一个例子添加。他们在SharePoint列表中动态添加基于关田,使他们能够以任意顺序,可以重复的。



<$ P $(我用鲜明的()去除这些) p> 列表<串GT; monthList =新的List<串GT;();
monthList.Add(六一);
monthList.Add(二月);
monthList.Add(八五);



想重新排序此为:

 二月
六月
八月


解决方案

您可以解析字符串转换成的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();

这篇关于在一个列表中排序个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆