Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#LINQ创建月份和年份列表_C#_.net_Linq - Fatal编程技术网

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

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

我有一个属性为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 => 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);
}