【问题标题】:Join, Group By and Aggregate with LINQ使用 LINQ 加入、分组和聚合
【发布时间】:2014-09-25 18:22:11
【问题描述】:

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


        }

【问题讨论】:

    标签: c# linq join group-by aggregate


    【解决方案1】:

    基本上只是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多