Linq,如何进行分组? [英] Linq, How to do groupBy?
问题描述
项目表:
编号,部门编号,年份,名称,级别
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.
I have a project table. I need to get the project for each dept for 2001. for DeptId = 2, it has no project for 2001, I need to show previous year project which is 2000.
我的linq应该返回以下结果.
my linq should return following result back.
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进行分组,但不确定如何编写此查询.
I was thinking about using groupby, group the DeptId, but not sure how to write this query.
更新:
这是我尝试过的.
var projects = project.Where(x => x.Year == 2001)
var projects = project.Where(x=>x.Year == 2001)
但是对于DeptId = 2,这将不会返回结果,这就是为什么我在考虑使用groupby的原因,但是却不知道如何编写它.
but this will not return result for DeptId = 2, that's why I am thinking about using groupby, but clueless how to write it.
推荐答案
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();
这篇关于Linq,如何进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!