wasAsked.

Write LINQ query to get , where the amount is Greater than 100 and Sum of all orders

EPAM · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

Assume an Order class with an Amount property. Filter orders above 100 and sum them: var largeOrders = orders.Where(o => o.Amount > 100).ToList(); decimal totalOfLargeOrders = largeOrders.Sum(o => o.Amount); Or directly, without materialising the list: decimal total = orders.Where(o => o.Amount > 100).Sum(o => o.Amount); Query syntax: decimal total2 = (from o in orders where o.Amount > 100 select o.Amount).Sum(); If the question means "sum of all orders" as a separate figure: decimal grandTotal = orders.Sum(o => o.Amount); var summary = new { LargeOrders = orders.Where(o => o.Amount > 100).ToList(), LargeTotal = orders.Where(o => o.Amount > 100).Sum(o => o.Amount), GrandTotal = grandTotal }; Per customer (a common follow-up): var perCustomer = orders .Where(o => o.Amount > 100) .GroupBy(o => o.CustomerId) .Select(g => new { CustomerId = g.Key, Count = g.Count(), Total = g.Sum(o => o.Amount) }) .OrderByDescending(x => x.Total) .ToList(); With Entity Framework Core (runs in SQL): decimal dbTotal = await db.Orders .Where(o => o.Amount > 100) .SumAsync(o => o.Amount, ct); // SELECT COALESCE(SUM(Amount), 0) FROM Orders WHERE Amount > 100 Points worth mentioning - Use decimal for money, not double, to avoid rounding errors. - Sum on an empty sequence returns 0 for non-nullable types. In EF Core, SumAsync over an empty set also returns 0 for non-nullable properties. - Avoid enumerating the same query twice when you need both the list and the sum: materialise once with ToList(), then compute from the list, or compute both in one GroupBy or Aggregate. - With EF Core, filter and aggregate in the database rather than loading all orders into memory.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics