Linq to SQL 中按一年中的周(周数)分组
在常规 SQL 中,我可以执行类似的操作:
SELECT * From T GROUP BY DATEPART(wk, T.Date)
如何在 Linq to SQL 中执行此操作?
以下不起作用
From F In DB.T Group R By DatePart(DateInterval.WeekOfYear, F.Date)
也不起作用:
From F In DB.T Group R By (F.Date.DayOfYear / 7)
In regular SQL i could do something like
SELECT * From T GROUP BY DATEPART(wk, T.Date)
How can i do that in Linq to SQL ?
The following don't work
From F In DB.T Group R By DatePart(DateInterval.WeekOfYear, F.Date)
Also don't work:
From F In DB.T Group R By (F.Date.DayOfYear / 7)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
LINQ to SQL 不支持 Calendar.WeekOfYear 方法,但您可能会创建一个 TSQL 包装对 DatePart 调用的函数 。 DayOfYear / 7 技巧应该适用于大多数情况,并且更容易使用。这是我最终得到的代码:
结果如下:
LINQ to SQL does not support the Calendar.WeekOfYear method, but you could potentially create a TSQL function that wraps the call to DatePart. The DayOfYear / 7 trick should work for most cases and is much easier to use. Here's the code I ended up with:
Results in something like this:
您可以使用 System.Data.Entity.SqlServer 命名空间。
You can use the
SqlFunctions.DatePart
method from the System.Data.Entity.SqlServer namespace.范围变量名称只能从不带参数的简单名称或限定名称推断
Range variable name can be inferred only from a simple or qualified name with no arguments
这工作正常。
您错误地指定了组。该代码的结果是对象的集合。每个对象都有一个 Key 属性,该属性将是您分组的依据(在本例中为
F.Date.DayOfYear / 7
的结果)。每个对象将是来自 T 的满足该组的对象的集合健康)状况。This works correctly.
You were specifying the group by incorrectly. The result of this code be a collection of objects. Each object will have a Key property which will be what you grouped by (in this case the result of
F.Date.DayOfYear / 7
. Each object will be a collection of objects from T that met the group condition.如果您担心您所在的文化,以下代码将考虑到这一点:
If you are concerned about the culture you are in the following code will take that into account:
首先,您应该获取一周中第一天的日期。
获取一周中第一天的日期。
您可以使用此代码:
然后您可以按一周的第一个日期进行分组。
所以常规 SQL 中的这段代码:
可以在 Linq to SQL 中像这样完成
First you should get the date of the first day in the week.
To get the date of the first day in the week.
you can use this code:
Then you can group by the first date of the week.
So this code in regular SQL :
can be done in Linq to SQL like this