使用LINQ进行Join、Group By和Aggregate

本文关键字:By Aggregate Group LINQ 进行 Join 使用 | 更新日期: 2023-09-27 18:24:42

我对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

        }

使用LINQ进行Join、Group By和Aggregate

基本上只是

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;
    }