我如何仅在LINQ查询中的datetime日期使用group by

Shr*_*hri 4 c# linq asp.net datetime date

我有这个LINQ查询

var data = (from orders in db.Orders
        group orders by orders.OrderDate into dateGroup
        select new OrderDateGroup()
        {
            OrderDate = dateGroup.Key,
            OrderCount = dateGroup.Count()
        }).Take(10);
Run Code Online (Sandbox Code Playgroud)

orders.OrderDate是DateTime但我想只根据Date进行分组

Far*_*yev 7

您可以使用规范函数:

group orders by EntityFunctions.TruncateTime(orders.OrderDate) into dateGroup
Run Code Online (Sandbox Code Playgroud)

附加信息:

EntityFunctions方法称为规范函数.这些是一组功能,所有实体框架提供程序都支持这些功能.这些规范函数将转换为提供程序的相应数据源功能.规范函数是访问核心语言之外的功能的首选方法,因为它们使查询可移植.

你可以找到所有经典功能在这里和所有的日期和时间规范函数在这里.

此外,不要忘记包括System.Data.Objectsnamepsace System.Data.Entity.dll.

注意:
如果您使用的是EF6,则必须考虑更改EntityFunctionsDbFunctions.并且不要忘记包括System.Data.Entity来自的名字EntityFramework.dll.