Linq,怎么办groupBy?

时间:2012-10-14 23:46:44

标签: linq linq-to-sql

项目表:

Id,DeptId,Year,Name,Level

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,但是如何编写它是无能为力的。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

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());