【问题标题】:C# LINQ create month and year listC# LINQ 创建月份和年份列表
【发布时间】:2016-10-13 21:56:12
【问题描述】:

我有一组传单,其属性 FlyerDate 作为日期时间,我想创建一个包含月份和年份的下拉列表,例如“2015 年 11 月、2015 年 12 月、2016 年 1 月”...

这是我的代码:

var monthList = flyers.Where(i => i.FlyerDate != DateTime.MinValue && i.FlyerDate.Year >= 2013)
    .GroupBy(i => i.FlyerDate.Month)
    .Select(g => new { 
        Month = g.Key, 
        Year = g.First(i => i.FlyerDate != DateTime.MinValue).FlyerDate.Year, 
        FullDate = String.Concat(DateTimeFormatInfo.CurrentInfo.GetMonthName(g.Key), " ", g.First(i => i.FlyerDate != DateTime.MinValue).FlyerDate.Year), 
        Total = g.Count(i => i.FlyerID > 0) 
    }
);

我希望GroupBy 在月份和年份都有效,因为在我的情况下,列表仅包含每个月的第一次出现。有什么提示吗?

【问题讨论】:

  • i.FlyerDate != DateTime.MinValue 由于第二个条件不需要
  • .GroupBy(i => i.FlyerDate.Month * 10000 + i.FlyerDate.Year)

标签: c# .net linq


【解决方案1】:

您需要按包含年份和月份的匿名类型进行分组:

var monthList = flyers.Where(i => i.FlyerDate.Year >= 2013)
    .GroupBy(i => new { i.FlyerDate.Year, i.FlyerDate.Month })
    .Select(g => new { 
        Year  = g.Key.Year,
        Month = g.Key.Month, 
        FullDate = DateTimeFormatInfo.CurrentInfo.GetMonthName(g.Key.Month) + " " + g.Key.Year
    });

顺便说一句,如果您想要缩写的月份名称,因为您想要的结果表明您需要使用 DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName 而不是 GetMonthName。

【讨论】:

    【解决方案2】:

    我怀疑您的问题可能是GroupBy(i => i.FlyerDate.Month) 子句。该分组似乎不尊重年份,因此当您到达 Select 时,您将只剩下 12 个组。

    将年份合并到 GroupBy lambda 可以为每个月创建一个独特的组。假设您的 Month 和 Year 是 ints:

    .GroupBy(i => (i.FlyerDate.Year * 12) + i.FlyerDate.Month)
    

    可能是一个不错的起点。

    【讨论】:

      【解决方案3】:
      var query = flyers.GroupBy(f => f.FlyerDate.ToString("MMM yyyy"))
      
      foreach (var group in query)
      {
          Console.WriteLine(group.Key);
          foreach (Flyer f in group)
              Console.WriteLine(f.FlyerDate);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多