Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq group by date when using multiple group by fields [duplicate]

Since linq does not allow you to use the Date() method inside a linq query, I read about using DbFunctions.TruncateTime, which works fine until you try using it inside an anonymous type which is what I need to do in order to group on multiple fields. I also tried creating a new datetime using just the date portion of my field but this doesn't work either (again with the same error).

My query looks like

kw = kw
    .GroupBy(x => new { DbFunctions.TruncateTime(g.SummaryHour), x.KeywordID })
    .SelectMany(x => x)
    .OrderByDescending(x => x.KeywordID);

I tried chaining the group by's together like groupby.groupby... but this doesn't give me the same result. Any way I can achieve this? I'm basically trying to filter out the time portion of my date and group by other fields as well.

like image 972
KingOfHypocrites Avatar asked May 01 '26 10:05

KingOfHypocrites


1 Answers

Sure you can use a method in an anonymous type, but you have to supply the name of the property, because the compiler doesn't have anything to derive it from:

kw.GroupBy(x => new { 
                      Date = DbFunctions.TruncateTime(g.SummaryHour),
                      x.KeywordID
                    })
like image 193
Gert Arnold Avatar answered May 03 '26 00:05

Gert Arnold