Linq: How to calculate the sales Total price and group them by product
- by Daoming Yang
I have a order list and I want to generate and rank the product with its total sales and quantity. With @tvanfosson's help, I can bring the grouped product detail with the following code, but how can I calculate and add up the total sales and quantity into each productListResult's object?
Can anyone help me with this?
Many thanks.
var orderProductVariantListResult = productList.SelectMany(o => o.OrderProductVariantList)
.Select(opv => new {
Product = opv.ProductVariant.Product,
Quantity = opv.Quantity,
PriceSales = opv.PriceSales,
Sales = opv.Quantity * opv.PriceSales,
});
var productListResult = orderProductVariantResult
.Select(pv => pv.Product)
.GroupBy(p => p)
.Select(g => new
{
Product = g.Key,
TotalOrderCount = g.Count()
})
.OrderByDescending(x => x.TotalOrderCount).ToList();