繁体   English   中英

LINQ-组/求和多列

[英]LINQ - group/sum multiple columns

数据是本地CSV文件,可通过OleDB加载到ado.net数据集中。 该表有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), 2)),
                } );

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

谷歌“ linq推迟执行”,很漂亮;-)

但是正如Uriil所说,您可以将语句合并为一个linq查询:

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"],
        }
 )
 .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), 2)),
            } 
 );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM