2014-02-22 56 views
10

数据是被加载到经由OLEDB一个ado.net数据集的本地CSV文件。该表包含40列以上的发票明细。每一行都是发票中的一个单独的行项目,它可以由1到n行组成。LINQ - 基团/总和多列

该查询被用来组发票细节成每个发票单排,共计发票金额和平衡所致。

下工作,我尝试以确定: 是否有可能做到这一点在单个查询?

//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)), 
       }); 
+2

你可以把第一的GroupBy后立即选择,而不引入invoiceTotals的可变 – Uriil

+0

可能重复的[组按多个列(http://stackoverflow.com/questions/847066/group-by-multiple-columns) – psubsee2003

回答

23

你,其实只是做一个查询,当您使用结果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)), 
      } 
); 
+0

AH-感谢您的帮助。 'linq延期执行'之前没有听过这个词。我很欣赏投入和帮助。 – topry

+0

Whoo.Thats最好的,我曾经在栈得到了所有的答案。(Y) – RachitSharma