2014-02-22 55 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