数据是本地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)),
} );
答案 0 :(得分:37)
事实上,当您使用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)),
}
);