Reputation: 5832
I am kinda new to LINQ and I am trying to write the SQL below into a LINQ statement.
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. Any help is appreciated. Thanks
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
}
Upvotes: 1
Views: 2204
Reputation: 32266
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;
}
Upvotes: 3