3

我对 Linq 查询很陌生,我只想将我的数据库查询转换为 Linq。

这是我的简单 SQL 查询:

var query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
          + "FROM Person "
          + "WHERE EnrollmentDate IS NOT NULL "
          + "GROUP BY EnrollmentDate";

var data = db.Database.SqlQuery<EnrollmentDateGroup>(query);

工作正常,但是怎么可能在 Linq 中编写这个查询,我只是无法将group by语句转换为 Linq。转换成 Linq 似乎有些棘手。

谁能帮我这个?

4

2 回答 2

15
var query = from row in db.Person
            where row.EnrollmentDate != null
            group row by row.EnrollmentDate into grp
            select new {
                EnrollmentDate = grp.Key,
                Count = grp.Count()
            };
于 2013-05-16T07:13:20.623 回答
11
var result = db.Person
               .Where(r=> r.EnrollmentDate != null)
               .GroupBy(r=> r.EnrollmentDate)
               .Select( group=> new 
                              {
                                 EnrollmentDate = group.Key, 
                                 Count = group.Count()
                               });
于 2013-05-16T07:12:11.883 回答