首页 > 解决方案 > 需要帮助在 C# 中进行分组

问题描述

我有以下代码按发票号码分组付款金额和

我尝试将以下代码分组,InvoiceNumber如下所示,但出现InvalidOperationException: The LINQ expression GroupByShaperExpression'异常。

我要完成

 Type       Amount    InvoiceNumber
 1                 $100       123
 2                 $50        123
 3                 $100       123
 4                 $1200      123
 1                 $100       124
 1                 $300       124
 3                 $100       124
 3                 $300       124
 4                 $100       124

我想按发票编号分组并将类型 = 1&2 的金额字段的值相加并显示为利息,将 3&4 显示为 Princepal

InvoiceNumber       Interest   Princepal
123                 $150        $1300
124                 $400        $500

标签: c#.netentity-frameworklinq

解决方案


有几个问题:

  • EF Core 之后无法访问导航属性GroupBy
  • 即使 EF Core 可以翻译此查询,它也是无效的。

考虑用以下方式重写查询:

var ProductPaymentIDs = ProductPayments.Select(pp => pp.ID).ToList();

var query =
    from cl in Context.PaymentCodingLines
    where ProductPaymentIDs.Contains(cl.ProductPaymentID)
    group new { cl.InvoiceLineNav.TypeID, cl.Amount } by g.InvoiceLineNav.InvoiceNav.InvoiceNumber into g
    select new DetailDTO
    {
        InvoiceNumber = g.Key,
        InterestPaid = g.Sum(x => x.TypeID == 1 || x.TypeID == 2 ? x.Amount : 0),
        PrincipalPaid = g.Sum(x => x.TypeID == 3 || x.TypeID == 4 ? x.Amount : 0)
    };

var Details = query.ToList();

推荐阅读