我有一组传单,其属性 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/