5

enter image description here

I need to group per week based on the registration date ?

2
  • i think you need to research how to do group by in linq, this just looks wrong, what more interesting is i dont even see registration date in your group by. i suggest you download linqpad and get it to work in that. Also to make it clear what you intent is, just supply the SQL which you would like the linq for its to hard trying to work out what you want
    – Seabizkit
    Nov 14, 2018 at 19:10
  • 1
    The date is Trsdt which is also in the condition Nov 14, 2018 at 19:12

2 Answers 2

8

It's not quite clear what CalendarWeekRule do you have in mind, so assuming you want the simplest (FirstDay), i.e. the formula like

Week = 1 + (DateTime.DayOfYear - 1) / 7

EF Core supports translation of the DayOfWeek to SQL, so you could use something like this (not sure if you need Year):

.GroupBy(g => new { g.Trsdt.Year, Week = 1 + (g.Trsdt.DayOfYear - 1) / 7 })
4
  • I use MySql as DBServer and such a grouping doesn't work.
    – Timothy
    Aug 12, 2022 at 9:34
  • @Timothy Too bad. By "doesn't work" I guess you mean the MySql database provider does not support DayOfWeek translation. Btw, there are at least two MySQL database providers - one from Oracle and another called Pomelo, not sure which one are you using, but in general Pomelo has better support.
    – Ivan Stoev
    Aug 12, 2022 at 16:33
  • I use Pomelo. By the way I've tested this formula with manually created list, and it works perfectly
    – Timothy
    Aug 12, 2022 at 17:13
  • Works with Postgres too! Nov 2, 2022 at 16:05
1

using System.Globalization;

 .GroupBy( 
              g => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear( g.Trsdt, 
              CalendarWeekRule.FirstDay,DayOfWeek.Monday )
           )
1
  • 1
    Sadly this can't be translated to a sql query. Jan 3 at 11:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.