Linq:使用基于字符串的let语句对数据进行分组

Linq: using let statement based on string to group data

这是我的场景...

假设我有这个 class(称为 nf)w/values:

MyDate,Tons,ClientCode
25/12/2020,10,A
26/12/2020,5,A
27/12/2020,5,A
14/12/2020,7,A
11/12/2020,3,A

所以我写了下面的代码来对结果进行分组。

   List<HC> nfs = (from n in ctx.nf
                   where n.ClientCode.StartsWith(CLIENT_CODE_STR)
                   let quinzena = $"{n.MyDate.Year}/{n.MyDate.Month}/{(n.DataEmissao.Day >= 1 && n.MyDate.Day <= 15 ? "1QZ" : "2QZ")}"
                   group n by new { quinzena } into g
                   select new { qnz = g.Key.quinzena, totalc = g.Sum(x => x.Tons) }
                  ).Take(12)
                  .OrderByDescending(a => a.qnz)
                  .AsEnumerable()
                  .Select(r=> new HC{ Period = r.qnz, TotalTons = r.totalc }).ToList();

预期结果是:

Period,TotalTons
2020/12/1QZ,10
2020/12/2QZ,20

重点是 let 语句...用于正确分组数据... 代码运行时出现此错误...

LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object, System.Object)' method, and this method cannot be translated into a store expression.

有没有办法进行这种分组?? 非常感谢

为什么不将这些值分开,直到您需要在内存中组合它们。

List<HC> nfs = (from n in ctx.nf
               where n.ClientCode.StartsWith(CLIENT_CODE_STR)
               let q = n.DataEmissao.Day >= 1 && n.MyDate.Day <= 15 ? "1QZ" : "2QZ"
               group n by new { n.MayDate.Year, n.MayDate.Month, Q = q } into g
               select new { qnz = g.Key, totalc = g.Sum(x => x.Tons) }
              ).Take(12)
              .OrderByDescending(a => a.qnz.Year)
              .ThenByDescending(a => a.qnz.Month)
              .ThenByDescending(a => a.qnz.Q)
              .AsEnumerable()
              .Select(r=> new HC
              { 
                  Period = $"{r.qnzYear}/{r.qnz.Month}/{r.qnz.Q}", 
                  TotalTons = r.totalc 
              })
              .ToList();