How to group by in LINQ?

.net, c#, entity-framework, linq, linq-to-sql

Solution

This should be roughly there although this is off the top of my head as not at an IDE.

var result = context.Notes
                    .Where(n => [Your where clause])
                    .GroupBy(n => new { n.IDUser, n.IDAppointment, n.AppointmentDate})
                    .Select(g => new {
                                   g.Key.IDAppointment,
                                   g.Key.IDUser,
                                   g.Sum(n => n.DurationInHours)});

UPDATE:

For reference your where clause will be something like this... (again off the top of my head)

DateTime lastMonth = DateTime.Today.AddMonths(-1);
int userId = 1 // TODO: FIX
var result = context.Notes.Where(n => n.AppointmentDate > lastMonth
                                   && n.IDUser = userId)

Resulting in....

DateTime lastMonth = DateTime.Today.AddMonths(-1);
int userId = 1 // TODO: FIX
var result = context.Notes
                    .Where(n => n.AppointmentDate > lastMonth
                             && n.IDUser = userId)
                    .GroupBy(n => new { n.IDUser, n.IDAppointment, n.AppointmentDate})
                    .Select(g => new {
                                   g.Key.IDAppointment,
                                   g.Key.IDUser,
                                   g.Sum(n => n.DurationInHours)});

Problem

I need to return the last 30 days of a speciefic user daily appointments and check if the user made at least 8 hours of appointments for each day. in sql i can do that with this command: ``` select IDAppointment,IDUser, SUM(DurationInHours) from Note where AppointmentDate > *lastmonth and IDUser = @userID group by IDUser,IDAppointment,AppointmentDate ``` and after that i get the result and validate the DurationInHours(double type). Is it possible to do it using LINQ? Get the list of the last month user appointments and validate it day by day Thanks!

Original source

Related problems