【问题标题】:Sorting a List of Month Names Starting with Current Month [duplicate]对从当前月份开始的月份名称列表进行排序[重复]
【发布时间】:2012-10-18 10:35:35
【问题描述】:
【问题讨论】:
标签:
c#
date
sorting
datetime
【解决方案1】:
string[] months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
var ordered = months.Skip(DateTime.Today.Month - 1)
.Concat(months.Take(DateTime.Today.Month - 1))
.Where(s=>!String.IsNullOrEmpty(s))
.ToList();
【解决方案2】:
使用DateTimeFormatInfo.GetMonthName methoed
List<string> list = new List<string>();
DateTimeFormatInfo dtFI = new DateTimeFormatInfo();
DateTime currentDate = DateTime.Now;
DateTime nextyearDate = currentDate.AddYears(1).AddDays(-1);
while (currentDate < nextyearDate)
{
list.Add(dtFI.GetMonthName(currentDate.Month));
currentDate = currentDate.AddMonths(1);
}
这将创建一个新的月份列表,从当前月份开始。
【解决方案3】:
使用 LINQ 对此的另一种看法:
// month name source, use what you prefer
var monthNames = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
var sorted = Enumerable.Range(1, 12).Zip(monthNames, Tuple.Create)
.OrderBy(t => (t.Item1 - DateTime.Today.Month + 12) % 12)
.Select(t => t.Item2)
.ToArray();
【解决方案4】:
您可以使用 List<DateTime> monthNames = DateTimeFormatInfo.CurrentInfo.MonthNames.ToList(); 获取 C# 中的月份列表。它得到一个带有 13 个元素的 List<DateTime>(末尾为空月份名称,但您始终可以删除最后一个元素 monthNames.RemoveAt(monthNames.Count - 1);
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx
要重新排序此列表,您可以使用DateTime.Now.Month.ToString("00"); 获取当前月份编号索引,并重组列表newMonthNames = monthNames.GetRange(index, 12 - index).AddRange(monthNames.GetRange(0, index);
有很多方法可以做到这一点,就像其他人所展示的那样。