C#LINQ创建月份和年份列表
我有一个属性为datetime的传单集合C#LINQ创建月份和年份列表,c#,.net,linq,C#,.net,Linq,我有一个属性为datetime的传单集合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
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.get缩写的月份名称
,而不是GetMonthName
我怀疑您的问题可能是GroupBy(I=>I.FlyerDate.month)
子句。该分组似乎与年份无关,因此当您进入Select
时,只剩下12个分组
将年份合并到GroupBy
lambda可以为每个月创建一个独特的组。假设您的月份
和年份
为int
s:
.GroupBy(i => (i.FlyerDate.Year * 12) + i.FlyerDate.Month)
可能是一个很好的起点。
i.FlyerDate!=由于第二个条件.GroupBy(i=>i.FlyerDate.Month*10000+i.FlyerDate.Year),不需要DateTime.MinValue
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);
}