mercredi 4 février 2015

LINQ GroupBy with Sum


Vote count:

0




I'm trying to get a client's most popular products (ordered the most by quantity) using a LINQ query. I have the right results when I run this SQL query:



SELECT TOP(15) i.ProductId, p.Description, Sum(i.Quantity) As QuantityOrdered FROM Orders o INNER JOIN OrderItems i ON o.Id = i.OrderId
INNER JOIN Products p ON i.ProductId = p.Id WHERE o.ClientId = 19 GROUP BY ProductId, Description ORDER BY QuantityOrdered DESC


It gives me the right results:


enter image description here


I'm trying to duplicate these results using LINQ and here is what I have so far:



var query = _context.Set<OrderItem>()
.Where(oi => oi.Order.ClientId == input.ClientId)
.GroupBy(oi => oi.ProductId)
.Select(group => group.Sum(item => item.Quantity)
).Take(15);


All I get here is a list of Sums, but I don't know how to include the product id and description. Secondly how do I include an OrderBy so that the highest sum appears first?



asked 1 min ago

Ray

282






LINQ GroupBy with Sum

Aucun commentaire:

Enregistrer un commentaire