简体   繁体   English

Linq Query获取最近x年中每年的最后一个条目

[英]Linq Query to get last entry of every year in the last x years

I have a table in an MSSQL table which contains usage data. 我在包含使用情况数据的MSSQL表中有一个表。 For a report I need to load only the last entry of every year in the last 10 years. 对于报告,我只需要加载过去10年中每年的最后一个条目。

Example

ID |    Hits    | GeneratedAt
 1 |     12     | 20171231 
 2 |     35     | 20161231
 3 |     5      | 20151230
 4 |     10     | 20141231

Is there a way a way to get this values using a single linq queries or can I combine multiple linq queries somehow? 有没有一种方法可以使用单个linq查询获取此值,或者可以以某种方式组合多个linq查询?

The idea I came up with was looking for december 31 but this will make problems of for any reason there is no entry for this date. 我想出的主意是在12月31日,但是由于任何原因,这个日期都会出现问题。 Instead the query should load the last avaible day (as in ID 3). 而是查询应加载最后一个可用的日期(如ID 3)。

private static IQueryable<Usage> GetYearValues(IQueryable<Usage> queryable)
{
    var firstYear = DateTime.Now.AddYears(-10);

    var yInfosArray = queryable
        .Where(
            s.GeneratedAt.Year >= firstYear.Year
            && s.GeneratedAt.Month == 12
            && s.GeneratedAt.Day == 31 || s.GeneratedAt >= today
        )
        .OrderByDescending(s => s.GeneratedAt);
    return yInfosArray;
}

Just sort by descending order, group by year and pick the first entry inside every group: 只需按降序排序,按年分组并在每个组中选择第一个条目:

queryable
    .Where(x => x.GeneratedAt.Year >= DateTime.Now.Year - n) // if this year doesn't count to last n years, remove the `=` sign
    .OrderByDescending(x => x.ID) // or, by x.GeneratedAt if the table isnt time sorted
    .GroupBy(x => x.GeneratedAt.Year, (year, g) => g.First()) // select last (first in desc) of each year

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM