C# LINQ 创建月份和年份列表

标签 c# .net linq

我有一组传单,其属性 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同时适用于月份和年份,因为在我的例子中,列表仅包含每个月的第一次出现。有什么提示吗?

最佳答案

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

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

关于C# LINQ 创建月份和年份列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40016535/

相关文章:

c# - 在基于 .Net 4.0 的应用程序中解码 JWT token

c# - LINQ(或)在循环中使用处理?选择什么?

c# - 可空类型是否适合我的情况?

c# - 线程窗体

c# - 登录状态不显示已登录

c# - CTP5 EF代码第一题

c# - 如何将 Linq 查询传递给方法?

c# - C#Monitor.Wait和VB6消息泵送和事件

c# - 如何将字符串列表拆分为较小的字符串列表 block

.net - 将多个数组聚合为一个数组 (Linq)