[英]How to sum the values of a specific column attribute of individual rows returned using a LINQ expression? (C#)
我想使用基于某个传递值的 LINQ 表达式来挑出表的行,然后对这些行中的每一行的特定列属性求和,同时保持行的各个总和彼此分开。
用户使用数量输入输入特定数量值 - 此传递的数量值需要在 LINQ 表达式中使用以过滤出满足所需条件的行。
下面是分配给传递的数量值的变量:
int quantitySelected;
JObject passedQuantity = JObject.Parse(data);
quantitySelected = (int)passedQuantity["qtySelect"]
“quantitySelected”现在等于用户传递的值 - 现在,在 LINQ 表达式中使用此值,我希望能够根据满足的条件过滤特定表(InvoiceLine),然后包括所有根据外键标识符 (ProductID) 过滤行:
var dynamicReader = DBAccessor.InvoiceLines.Where(zz => zz.Quantity >= quantitySelected).Include(yy => yy.ProductID);
我希望将数量大于或等于用户输入的所有行存储在动态读取器中,并参考它们关联的 ProductID。 例如:
我希望能够挑出 ProductID 为 8 的行(可以在这里看到两次),然后将它们的数量相加,(因此 ProductID 8 最终的总和为 6)等等(对于每个重复的 ProductID )。
有没有办法使用 LINQ 查询表达式来实现这一点? 还是我需要使用额外的 C#?
我希望能够挑出 ProductID 为 8 的行(可以在这里看到两次),然后将它们的数量相加
那很好。 显然你想要完整的行,在你想要 ProductId 和数量总和的行中。 但是你想用其他属性做什么:你想要 InvoiceLineId 7 还是 10? 发票 ID 3 还是 4? 或者你只对总和感兴趣?
我的建议是将具有相同 ProductId 的 InvoiceLine 分组。 为此,您可以使用 GroupBy。 使用参数 resultSelector 选择最终结果中所需的属性:
var result = DBAccessor.InvoiceLines
.Where(invoiceLine => invoiceLine.Quantity >= quantitySelected)
// group the remaining invoicelines into groups with the same productId
.GroupBy(invoiceLine => invoiceLine.ProductId,
// parameter result selector: use the common productId and all invoiceLines
// that have this productId to make one new:
(productId, invoiceLinesWithThisProductId) => new
{
ProductId = productId,
Quantity = invoiceLinesWithThisProductId
.Select(invoiceLine => invoiceLine.Quantity)
.Sum(),
... // other properties, you didn't specify what you want
});
阅读说明后,您似乎愿意将列表中的重复行合并为一个并总结重复行的数量。 您可以使用GroupBy
语句来获得所需的结果。
这是一个示例,您可以相应地进一步修复它以满足您的需求。
var dynamiceReader = DBAccessor.InvoiceLines.Where(x=> x.Quantity >= quantitySelected).GroupBy(e => e.ProductID).Select(product =>
{
var p = product.First();
return new
{
InvoiceLineID = p.InvoiceLineID,
InvoiceID = p.InvoiceID,
ProductID = p.ProductID,
Quantity = product.Sum(sum => sum.Quantity)
};
});
同样,如果您还想包含合并的 Id,那么您可以像下面这样修改它:
InvoiceLineID = string.Join(", ", product.Select(x => x.InvoiceLineID)),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.