Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ. Grouping by days. How to do this easily?

I can't seem to find any good reference on this. I have a lot of data in SQL with dates. So I wanted to make a line chart to show this data over time. If I want to show it over a period of days then I need to group by days.. But the LOGDATE is the full date.. not the DAY..

So I have this below, but LINQ doesn't know what 'DayOfYear' property is...

 var q = from x in dc.ApplicationLogs
                let dt = x.LogDate
                group x by new { dayofyear = dt.Value.DayOfYear } into g
                select new
                {
                    iCount = g.Count(),
                    strDate = g.Key
                };
like image 566
punkouter Avatar asked Feb 27 '23 20:02

punkouter


2 Answers

In EF core you can use DateTime.Date to get the date portion of a DateTime value.

In EF6 you can use DbFunctions.TruncateTime:

to return the given date with the time portion cleared

var q = from x in dc.ApplicationLogs
        let dt = x.LogDate.Date
        // EF6:let dt = DbFunctions.TruncateTime(x.LogDate)
        group x by dt into g
        select new
        {
            iCount = g.Count(),
            strDate = g.Key
        };
like image 141
Gert Arnold Avatar answered Mar 05 '23 17:03

Gert Arnold


You want .Date to get the date part of a DateTime not DayOfyear unless you are deliberately trying to put the same day of the year from each year into the group.

like image 37
Ian Mercer Avatar answered Mar 05 '23 17:03

Ian Mercer