【问题标题】:Conditional count group by in LINQ C#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().

有什么办法吗?

【问题讨论】:

    标签: c# linq group-by


    【解决方案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) 
        };
    

    【讨论】:

      猜你喜欢
      • 2014-11-20
      • 2010-11-01
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 2019-01-23
      相关资源
      最近更新 更多