【问题标题】:Sorting a List of Month Names Starting with Current Month [duplicate]对从当前月份开始的月份名称列表进行排序[重复]
【发布时间】:2012-10-18 10:35:35
【问题描述】:

可能重复:
Linq orderby, start with specific number, then return to lowest

我需要创建一个列出一年中月份的组合框,但需要它以 当前月份,然后按月份顺序排列其余月份,例如:

十月
十一月
十二月
一月
二月
三月
等等……

数据源是数据库中的月份列表,根据月份编号(即一月 = 1 等)进行编号,然后对其进行操作以给出日期时间

如何在 C# 中对这个列表进行排序,以便得到我想要的顺序?

TIA。

【问题讨论】:

标签: 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&lt;DateTime&gt; monthNames = DateTimeFormatInfo.CurrentInfo.MonthNames.ToList(); 获取 C# 中的月份列表。它得到一个带有 13 个元素的 List&lt;DateTime&gt;(末尾为空月份名称,但您始终可以删除最后一个元素 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);

        有很多方法可以做到这一点,就像其他人所展示的那样。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-06-23
          • 1970-01-01
          • 2019-08-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-25
          相关资源
          最近更新 更多