Add additional fields to Linq group by

73 views Asked by At

I have the LINQ to SQL as below, which works fine.

        var qry = (from h in dc.Timesheets
                   join s in dc.Users on h.UserID equals s.UserID
                   join ug in dc.UserGroups on s.UserGroupID equals ug.UserGroupID
                   where h.BookedOn >= _dateFrom.Value && h.BookedOn <= _dateTo.Value
                   group h by ug.UserGroupID into g
                   orderby g.Count() descending
                   select new
                   {
                       UserGroupingID = g.Key,
                       BookingsPerDay = g.Count() / days
                   }).ToList();

Now I want to add the name of the User Group, but somehow I struggle to get the LINQ right. My limited knowledge tells me I should add the Description to the Group clause as follow, but it's a no-go:

I try:

    var qry = (from h in dc.Timesheets
               join s in dc.Users on h.UserID equals s.UserID
               join ug in dc.UserGroups on s.UserGroupID equals ug.UserGroupID
               where h.BookedOn >= _dateFrom.Value && h.BookedOn <= _dateTo.Value
               group h, GroupDescription = ug.Description by ug.UserGroupID into g
               orderby g.Count() descending
               select new
               {
                   UserGroupingID = g.Key,
                   Description = g.Key.GroupDescription
                   BookingsPerDay = g.Count() / days
               }).ToList();

Error: Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer' because it is not a delegate type

2

There are 2 answers

1
Melvin On

Shouldn't it be an == for the GroupDescription? And aren't you missing a comma in the select new statement?

4
PrinceT On

I think you might missing the new keyword here!!

 var qry = (from h in dc.Timesheets
           join s in dc.Users on h.UserID equals s.UserID
           join ug in dc.UserGroups on s.UserGroupID equals ug.UserGroupID
           where h.BookedOn >= _dateFrom.Value && h.BookedOn <= _dateTo.Value
           group new {h, GroupDescription = ug.Description} by new {GroupDescription} into g
           orderby g.Count() descending
           select new
           {
               UserGroupingID = g.Key,
               Description = g.Key.GroupDescription
               BookingsPerDay = g.Count() / days
           }).ToList();