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?

0

2 Answers 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()
            };
Sign up to request clarification or add additional context in comments.

1 Comment

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
11
var result = db.Person
               .Where(r=> r.EnrollmentDate != null)
               .GroupBy(r=> r.EnrollmentDate)
               .Select( group=> new 
                              {
                                 EnrollmentDate = group.Key, 
                                 Count = group.Count()
                               });

4 Comments

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, what is the class representing your table Person in your model ? Replace that in your query
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<EnrollmentDateGroup> (by adding ToList<EnrollmentDateGroup>() at tail), but didnt worked, Y ?
@ashok_damani, I can't see your edit, but for your answer of converting it to List<EnrollmentDateGroup> is not allowed since you are selecting an anonymous object using new keyword

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.