Group by Week of the Year (Week Number) in Linq to SQL

In regular SQL, I could do something like

SELECT * From T GROUP BY DATEPART(wk, T.Date)

How can I do this in Linq to SQL?

The following steps do not work

From F In DB.T Group R By DatePart(DateInterval.WeekOfYear, F.Date)

Also do not work:

From F In DB.T Group R By (F.Date.DayOfYear / 7)
+5
source share
6 answers

LINQ to SQL Calendar.WeekOfYear, TSQL DatePart. DayOfYear/7 . , :

var x = from F in DB.T
        group F by new {Year = F.Date.Year, Week = Math.Floor((decimal)F.Date.DayOfYear / 7)} into FGroup
        orderby FGroup.Key.Year, FGroup.Key.Week
        select new {
            Year = FGroup.Key.Year,
            Week = FGroup.Key.Week,
            Count = FGroup.Count()
        };

:

Year    Week    Count
2004    46      3
2004    47      3
2004    48      3
2004    49      3
2004    50      2
2005    0       1
2005    1       8
2005    2       3
2005    3       1
2005    12      2
2005    13      2
+7

.

from F in DB.T group F by F.Date.DayOfYear / 7;

. . Key, ( F.Date.DayOfYear / 7). T, .

+1

, , :

var ci = CultureInfo.CurrentCulture;
var cal = ci.Calendar;
var rule = ci.DateTimeFormat.CalendarWeekRule;
var firstDayOfWeek = ci.DateTimeFormat.FirstDayOfWeek;

var groups = from F in DB.T
             group F by cal.GetWeekOfYear(F, rule, firstDayOfWeek) into R
             select R;
0

.

Get the date of the first day of 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.

So this code in plain SQL:

SELECT * From T GROUP BY DATEPART(wk, T.Date)

can run in linq to sql like this

T.GroupBy(i => i.Date.StartOfWeek(DayOfWeek.Monday));
0
source

You can use the method SqlFunctions.DatePartof space names System.Data.Entity.SqlServer .

// Return the week number
From F In DB.T Group R By SqlFunctions.DatePart("week", F.Date)
0
source

All Articles