1

项目表:

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 projects = project.Where(x=>x.Year == 2001)

但这不会返回 DeptId = 2 的结果,这就是为什么我正在考虑使用 groupby,但不知道如何编写它。

4

2 回答 2

3
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();
于 2012-10-15T00:26:16.563 回答
0
from l in context.Projects.Where(w => w.Year <= 2001 )
        group l by l.DeptId into depts
        select depts.LastOrDefault();

拉姆达版本:

    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());
于 2012-10-15T00:29:40.457 回答