LINQ:按日期(包括年份)分组



我的数据集看起来像这样:

FileName     Date 
ABC      -    01/10/16
DBC      -    01/11/16
ZYX      -    03/10/16
ABX2      -   01/10/17
IOS       -   01/09/17

如何将它们分组到月份组中,同时确保在子句中考虑年份?

我目前正在使用 LINQ 查询正在按月创建组,但不包括年份,所以我有一组 ABC、ZYX 和 ABX2。 即使ABX2是2017年的报告,但同月,所以应该在不同的组中。

我一直在尝试不同的方法来做到这一点,但到目前为止还没有成功。

        var newList = from x in list
                      group x
        by x.Properties.LastModified.Value.Month into lastMod
                      where lastMod.Count() > 1
                      select lastMod;

一旦我将它们放在单独的组中,我将找出最后写的哪一个并保存并删除其余的。我很困,在这个问题上呆了半天。将不胜感激新鲜的眼光。

您可以按复合年-月键进行分组,如下所示:

var newList = list
    .Where(x => x.Properties.LastModified.HasValue)
    .GroupBy(x => new {
        x.Properties.LastModified.Value.Month
    ,   x.Properties.LastModified.Value.Year
    })
    .Where(g => g.Count() > 1);

在访问其 Value 属性之前,需要确保 LastModified 具有非 null 值。

我目前无法对此进行测试,但我认为按包含月份和年份的匿名类型分组应该可以做到这一点。

var newList = from x in list
                          group x
            by new {x.Properties.LastModified.Value.Month, x.Properties.LastModified.Value.Year} into lastMod
                          where lastMod.Count() > 1
                          select lastMod;

最新更新