c# – LINQ – 组/总和多列

前端之家收集整理的这篇文章主要介绍了c# – LINQ – 组/总和多列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
数据是通过OleDB加载到ado.net数据集中的本地CSV文件.该表有40列,包括发票明细.每行是发票中的单独的行项目,可以由1到n行组成.

查询用于将发票详细信息分组为每个发票的单个行,总计发票金额和到期余额.

以下作品,我正在尝试确定:
是否可以在单个查询中执行此操作?

//group the invoices by invoicenumber and sum the total
//Zoho has a separate record (row) for each item in the invoice
//first select the columns we need into an anon array   
var invoiceSum =
    DSZoho.Tables["Invoices"].AsEnumerable()
    .Select (x => 
        new {  
            InvNumber = x["invoice number"],InvTotal = x["item price"],Contact = x["customer name"],InvDate = x["invoice date"],DueDate = x["due date"],Balance = x["balance"],} );
    //then group and sum
    var invoiceTotals =
        invoiceSum
        .GroupBy (s => new {s.InvNumber,s.Contact,s.InvDate,s.DueDate} )
        .Select (g => 
            new {
                InvNumber = g.Key.InvNumber,InvDate = g.Key.InvDate,DueDate = g.Key.DueDate,Contact = g.Key.Contact,InvTotal = g.Sum (x => Math.Round(Convert.ToDecimal(x.InvTotal),2)),Balance = g.Sum (x => Math.Round(Convert.ToDecimal(x.Balance),} );

解决方法

实际上,当您使用invoiceTotals的结果时,您只会执行一个查询.在您正在显示代码中,您甚至没有对数据库进行查询.

谷歌“linq延期执行”,这很漂亮;-)

但是如Uriil所说,您可以将语句组合成一个LINQ查询

var invoiceSum =
DSZoho.Tables["Invoices"].AsEnumerable()
.Select (x => 
    new {  
        InvNumber = x["invoice number"],}
 )
 .GroupBy (s => new {s.InvNumber,s.DueDate} )
 .Select (g => 
        new {
            InvNumber = g.Key.InvNumber,} 
 );
原文链接:https://www.f2er.com/csharp/93247.html

猜你在找的C#相关文章