c# - LINQ to SQL - 按天/周/月分组

标签 c# linq-to-sql group-by func

我已经为这个问题摸不着头脑了一段时间。假设我做了一个扩展方法,要按日期对项目列表进行分组,我想更改可能的分组,以便结果可以按天、周或月进行分组。

我想到了以下内容,但我不断收到以下错误:

Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL

方法:

public static IQueryable<IGrouping<MonthDateGroup, T>> GroupByDate<T>(
    this IQueryable<T> items,
    DateGroupFrequency grouping,
    Expression<Func<T, DateTime?>> func)
{
    var selector = func.Compile();
    IQueryable<IGrouping<MonthDateGroup, T>> grouped = null;

    if (grouping == DateGroupFrequency.Daily)
    {
        grouped = from a in items
                  let date = selector(a).Value
                  group a by new MonthDateGroup
                  {
                      Day = date.Day, Month = date.Month, Year = date.Year
                  } 
                  into g
                  select g;
    }
    //Rest of groupings...

我假设在查询中使用 Func 是导致错误的原因,是否可以生成这样的代码?

附言我仍在努力思考 Func 和表达式 :)

最佳答案

组语法不应该是:

group a by new MonthDateGroup
{
 a.Day = date.Day, a.Month = date.Month, a.Year = date.Year
}

关于c# - LINQ to SQL - 按天/周/月分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4679466/

相关文章:

c# - 对使用异步调用的 MassTransit 消费者进行单元测试

linq - 动态 Linq 帮助,不同的错误取决于作为参数传递的对象?

sql - ORA-00979 : not a GROUP BY expression

sql-server - 子查询 T-SQL 中的 GROUP BY

linq-to-sql - LINQ-SQL 重用 - CompiledQuery.Compile

MySQL DISTINCT 更多列

c# - 在 C# 中从图像的 EXIF 获取 GPS 数据

c# - 当引用的程序集同时引用 mscorlib 2.0.5.0 和 4.0.0.0 时如何让 roslyn 进行编译

c# - 使用 LinQ 每季度过滤数据

c# - Linq IN 运算符