LINQ C# 中的条件计数分组依据

Posted

技术标签:

【中文标题】LINQ C# 中的条件计数分组依据【英文标题】:Conditional count group by in LINQ C# 【发布时间】:2021-09-02 00:57:44 【问题描述】:

我有一个代码可以计算 7 天内的记录:

  var r=  (from t in _context.Services
         where
            t.ServiceDate.Date >= FirstDay.Date &&
            t.ServiceDate.Date <= SeventhDay.Date 
         group t by new  t.ServiceDate.Year, t.ServiceDate.Month, t.ServiceDate.Day, t.Solution  into g
         select new DateAndCoint 
          
             date = new DateTime(g.Key.Year, g.Key.Month, g.Key.Day),
             count = g.Count() )
         .ToList();

它工作正常,但我有一个名为 Solution (bool) 的字段,它指示记录是否完​​成

所以我喜欢计算完成的记录(哪个解决方案是正确的)除了上述计数? 我试过了:

countDone = g.Where(x=>x.Solution).Count()

但它给了我一个运行时错误

InvalidOperationException: The LINQ expression '(GroupByShaperExpression:
KeySelector: new 
Year = (DATEPART((year), (s.ServiceDate))),
Month = (DATEPART((month), (s.ServiceDate))),
Day = (DATEPART((day), (s.ServiceDate))),
Solution = (s.Solution)
,
ElementSelector:(EntityShaperExpression:
EntityType: Service
ValueBufferExpression:
(ProjectionBindingExpression: EmptyProjectionMember)
IsNullable: False
)
)
.Where(x => x.Solution)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().

有什么办法吗?

【问题讨论】:

【参考方案1】:

EF Core 5.x 支持此类Count。由于您的查询不起作用,您可以将Count 模拟为Sum

 var query = 
    from t in _context.Services
    where
        t.ServiceDate.Date >= FirstDay.Date &&
        t.ServiceDate.Date <= SeventhDay.Date 
    group t by new  t.ServiceDate.Year, t.ServiceDate.Month, t.ServiceDate.Day, t.Solution  into g
    select new DateAndCoint 
     
        date = new DateTime(g.Key.Year, g.Key.Month, g.Key.Day),
        count = g.Count(),
        countDone = g.Sum(x => x.Solution ? 1 : 0) 
    ;

【讨论】:

以上是关于LINQ C# 中的条件计数分组依据的主要内容,如果未能解决你的问题,请参考以下文章

Linq 按连接表中的项目计数分组

左外连接和多重计数 SQL to LINQ

哪个最快?计数子查询或分组依据

与计数、最大值和分组依据相关

内连接+计数+分组依据

Linq 高级分组 + 计数到新模型