【问题标题】:Linq, How to do groupBy?Linq,如何进行分组?
【发布时间】:2012-10-15 08:56:35
【问题描述】:

项目表:

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,但不知道如何编写它。

【问题讨论】:

    标签: linq linq-to-sql


    【解决方案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();
    

    【讨论】:

      【解决方案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());
      

      【讨论】:

      • 项目不按年份排序怎么办?
      猜你喜欢
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多