3

I'm quite new at Linq queries, I just want to convert my DB query into Linq.

Here is my simple SQL query:

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

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

It is working fine , but how could it possible to write this query in Linq, I just can't convert the group by statement into Linq. It seems somewhat tricky to convert into Linq.

Can anyone help me with this?

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
Ashok Damani
  • 3,896
  • 4
  • 30
  • 48

2 Answers2

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()
            };
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • thats cool!!! @Marc Gravell, thnx for ur answer, but i was looking for Linq in lamda expression as Habib's answer. but anyways thanx 4 a quick reply – Ashok Damani May 16 '13 at 07:33
11
var result = db.Person
               .Where(r=> r.EnrollmentDate != null)
               .GroupBy(r=> r.EnrollmentDate)
               .Select( group=> new 
                              {
                                 EnrollmentDate = group.Key, 
                                 Count = group.Count()
                               });
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
Habib
  • 219,104
  • 29
  • 407
  • 436
  • thanx for ur answer, but i am getting an `error(xyzModel.SchoolContext does not contain any defenition for Person)` the ques has been updated... plz see it again. thanx – Ashok Damani May 16 '13 at 07:29
  • @ashok_damani, what is the class representing your table `Person` in your model ? Replace that in your query – Habib May 16 '13 at 07:30
  • ur answer edited, now its working fine. but one more thing, i m writing here `Select( group=> new EnrollmentDateGroup()`, but as previous i tried it to convert into the `List` (by adding `ToList()` at tail), but didnt worked, Y ? – Ashok Damani May 16 '13 at 07:57
  • @ashok_damani, I can't see your edit, but for your answer of converting it to `List` is not allowed since you are selecting an [anonymous object](http://msdn.microsoft.com/en-us/library/vstudio/bb397696.aspx) using `new` keyword – Habib May 16 '13 at 07:59