C# LINQ-对多个列进行分组/求和
数据是通过OleDB加载到ado.net数据集中的本地CSV文件。该表包含40多列发票明细。每行是发票中的一个单独的行项目,可以由1到n行组成 查询用于将每张发票的发票明细分组为一行,合计发票金额和到期余额 以下是我想要确定的: 是否可以在单个查询中执行此操作C# LINQ-对多个列进行分组/求和,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 inv
//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延迟执行”,很漂亮;-) 但正如乌里尔所说,您可以将这些语句组合成一个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)),
}
);
您可以将GroupBy放在第一次选择之后,而无需引入invoiceTotals VariableAH的可能副本-谢谢您的帮助。”“林克延期执行”之前也没有听过这个词。我感谢你们的帮助。哇,这是我在书堆里得到的最好的答案