Search code examples
asp.netentity-frameworklinqlinq-to-entitiesasp.net-mvc-5

How to use groupby clause in Entity Framework and ASP.NET MVC 4?


I have an admission model class as follows:

public class admission
{
    public int AdmissionID {get;set;}
    public DateTime Session {get;set;}
    public string Class {get;set;}
    public DateTime RegDate {get;set;} 
}

I want to get the report of admission such that how many students are admitted to school each month in current year.

For example :

 Month    No.Of.StudentsAdmitted
---------------------------------
  Jan          20              
  Feb           2
  March        10
  April         5

 and so on....

Here is the query that I have tried but could not know what I'm exactly doing :

db.admissions
   .Where(d => d.regDateTime.Value.Date.Year == DateTime.Now.Year )
   .GroupBy(d => d.regDateTime.Value.Month)
   .ToList();

I also want the month name instead of month value.

In more simple words, I want to count the number of students in each month of the current year...


Solution

  • You're basically there. You have a list of Grouping, so just two steps remain to get what you want:

    Convert the int (month code) to the month name:

    var mo = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(g.Key);
    

    For each group, count the number of items in each group

    g.Count()
    

    putting it all together:

        var resultset = admissions
            .Where(dd => dd.RegDate.Date.Year == DateTime.Now.Year)
            .GroupBy(ddda => ddda.RegDate.Month)
            .Select(s => new
        {
            month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(s.Key),
            count = s.Count()
        }).ToList();
    

    Edit: In case EF complains, you can always move the ToList() up, then select the new anonymous object:

     var resultset = admissions
                .Where(dd => dd.RegDate.Date.Year == DateTime.Now.Year)
                .GroupBy(ddda => ddda.RegDate.Month)
                .ToList()
                .Select(s => new
                {
                    month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(s.Key),
                    count = s.Count()
                });