Linq, How to do groupBy?

前端 未结 2 963
鱼传尺愫
鱼传尺愫 2021-01-24 02:52

project table:

Id, DeptId, Year, Name, Level

Id = 1, DeptId = 1, Year = 2000, Name = \"ABC\", Level = 1
Id = 2, DeptId = 1, Year = 2001, Name = \"ABC1\",         


        
相关标签:
2条回答
  • 2021-01-24 03:39
    from l in context.Projects.Where(w => w.Year <= 2001 )
            group l by l.DeptId into depts
            select depts.LastOrDefault();
    

    Lambda version:

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

    Or alternatively:

        context.Projects.Where(w => w.Year <= 2001)
            .GroupBy(g => g.DeptId)
            .Select (s => s.OrderBy(o => o.Year).LastOrDefault());
    
    0 讨论(0)
  • 2021-01-24 03:47
    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();
    
    0 讨论(0)
提交回复
热议问题