简体   繁体   English

使用LINQ加入,分组和聚合

[英]Join, Group By and Aggregate with LINQ

I am kinda new to LINQ and I am trying to write the SQL below into a LINQ statement. 我是LINQ的新手,我正在尝试将下面的SQL写入LINQ语句。 It works except for the aggregate part in the SQL version ( COUNT(oec.CourseTitle) ), which I cannot figure out how to do that in LINQ. 它的工作原理除了SQL版本中的聚合部分( COUNT(oec.CourseTitle) ),我无法弄清楚如何在LINQ中做到这一点。 Any help is appreciated. 任何帮助表示赞赏。 Thanks 谢谢

SQL SQL

select 
oec.OnlineEducationCourseId, 
oec.CourseTitle,
COUNT(oec.CourseTitle) as CourseCount
from OnlineEducationRegistration as oer
join OnlineEducationCourse oec on oec.OnlineEducationCourseId = oer.OnlineEducationCourseId
where oer.District='K20'and DateCompleted BETWEEN '2013-01-01' AND '2014-01-01'
group by oec.CourseTitle,oec.OnlineEducationCourseId;

LINQ LINQ

var r = (from oer in db.OnlineEducationRegistrations
         join oec in db.OnlineEducationCourses on oer.OnlineEducationCourseId equals
         oec.OnlineEducationCourseId
         where oer.District == districtId && 
               oer.DateCompleted >= start && 
               oer.DateCompleted <= end
               group new {oer, oec} by new {oec.CourseTitle, oec.OnlineEducationCourseId}).ToList();



        foreach (var item in r)
        {
            var courseId = item.Key.OnlineEducationCourseId;
            var courseTitle = item.Key.CourseTitle;
            // aggregate count goes here


        }

Basically just 基本上只是

var courseCount = item.Count();

Or you could add it in a select 或者您可以将其添加到选择中

var r = (from oer in db.OnlineEducationRegistrations
         join oec in db.OnlineEducationCourses on oer.OnlineEducationCourseId equals
         oec.OnlineEducationCourseId
         where oer.District == districtId && 
               oer.DateCompleted >= start && 
               oer.DateCompleted <= end
         group new {oer, oec} by new {oec.CourseTitle, oec.OnlineEducationCourseId} into g
         select new {g.OnlineEducationCourseId, g.CourseTitle, CourseCount = g.Count() }).ToList();



    foreach (var item in r)
    {
        var courseId = item.OnlineEducationCourseId;
        var courseTitle = item.CourseTitle;
        var courseCount = item.CourseCount;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM