LINQ,怎么办GROUPBY?(Linq, How to do groupBy?)

2019-08-01 11:24发布

项目表:

ID,DEPTID,年份,名称,等级

Id = 1, DeptId = 1, Year = 2000, Name = "ABC", Level = 1
Id = 2, DeptId = 1, Year = 2001, Name = "ABC1", Level = 1
Id = 3, DeptId = 1, Year = 2002, Name = "ABC2", Level = 1

Id = 4, DeptId = 2, Year = 2000, Name = "ABC3", Level = 1
Id = 5, DeptId = 2, Year = 2002, Name = "ABC4", Level = 1

Id = 6, DeptId = 3, Year = 2000, Name = "ABC5", Level = 1
Id = 7, DeptId = 3, Year = 2001, Name = "ABC6", Level = 1
Id = 8, DeptId = 3, Year = 2002, Name = "ABC7", Level = 1

我有一个项目表。 我需要得到该项目的每个部门于2001年的DEPTID = 2,它有没有项目2001年,我需要出示前一年的项目是2000。

我的LINQ应该返回以下结果回来。

Id = 2, DeptId = 1, Year = 2001, Name = "ABC1", Level = 1
Id = 4, DeptId = 2, Year = 2000, Name = "ABC3", Level = 1
Id = 7, DeptId = 3, Year = 2001, Name = "ABC6", Level = 1

我想使用GROUPBY,组DEPTID,但不知道如何写这个查询。

更新:

这是我试过了。

VAR =项目project.Where(X => x.Year == 2001)

但是这不会对DEPTID = 2返回结果,这就是为什么我正在考虑使用GROUPBY,但无能怎么写。

Answer 1:

var query= from p in context.Projects
           group p by p.DeptId into grp
           select grp.Where(x => x.Year <= 2001)
                     .OrderByDescending(x => x.Year)
                     .FirstOrDefault();


Answer 2:

from l in context.Projects.Where(w => w.Year <= 2001 )
        group l by l.DeptId into depts
        select depts.LastOrDefault();

LAMBDA版本:

    context.Projects.Where(w => w.Year <= 2001)
        .GroupBy(g => g.DeptId)
        .Select (s => s.LastOrDefault());

或者:

    context.Projects.Where(w => w.Year <= 2001)
        .GroupBy(g => g.DeptId)
        .Select (s => s.OrderBy(o => o.Year).LastOrDefault());


文章来源: Linq, How to do groupBy?