使用LINQ加入,分组和聚合

时间:2014-09-25 18:22:11

标签: c# linq join group-by aggregate

我是LINQ的新手,我正在尝试将下面的SQL写入LINQ语句。 它的工作原理除了SQL版本(COUNT(oec.CourseTitle))中的聚合部分,我无法弄清楚如何在LINQ中这样做。任何帮助表示赞赏。感谢

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

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


        }

1 个答案:

答案 0 :(得分:3)

基本上只是

var courseCount = item.Count();

或者您可以将其添加到选择

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;
    }
相关问题