Linq to Entities group by week number

Or you can get the date of the first day in the week then group by that date.

To get the date of the first day in the week. you can use this code:

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
            diff += 7;
        }
        return dt.AddDays(-1 * diff).Date;
    }
}

then you can group by the first date of the week like this:

var groupedByWeek = salesOrdersList.GroupBy(i => i.DueDate.StartOfWeek(DayOfWeek.Monday));

Use SqlFunctions.DatePart() method:

var groupedByWeek = salesOrdersList.GroupBy(i => SqlFunctions.DatePart("week", i.DueDate));

It will add DATEPART sql function call into generated SQL query.


For daily:

var daily = salesOrdersList.Where(x => (long)(x.DueDate - new DateTime(1970, 1, 1, 0, 0, 0)).TotalDays == (long)(Datetime.Now.ToLocalTime()- new DateTime(1970, 1, 1, 0, 0, 0)).TotalDays ).ToList();

OR

var daily = salesOrdersList.Where(x => x.DueDate.Day == Datetime.Now.ToLocalTime().Day).ToList();

For Weekly:

var weekly = salesOrdersList.Where(x => (long)(x.DueDate - new DateTime(1970, 1, 1, 0, 0, 0)).TotalDays / 7 == (long)(Datetime.Now.ToLocalTime()- new DateTime(1970, 1, 1, 0, 0, 0)).TotalDays / 7).ToList();

For Monthly

var monthly= salesOrdersList.Where(x => x.DueDate.Month== Datetime.Now.ToLocalTime().Month).ToList();