.net core 2.2 sum results

simple question/answer hopefully since I cannot wrap my head around the syntax and how to do this.

I am populating a grid with the code below:

public IActionResult OrderBestSellersByQuantity()
{
var ordersList = _orderService.SearchOrders(customerId: _workContext.CurrentCustomer.Id);

        var orders = ordersList.ToList().Select(x => new BestsellerModel
        {
            ProductName = x.OrderItems.First().Product.Name,
            TotalQuantityInt = x.OrderItems.First().Quantity,
            TotalAmount = _priceFormatter.FormatPrice(x.OrderItems.First().UnitPriceInclTax, true, false) 
        }).OrderByDescending(o => o.TotalQuantityInt);
        return Json(orders);
    }

I would like to sum Quantity and sum the price. I think my problem here is I’m returning all records one by one and I don’t think Sum is possible in this case. Anyone here knows of a better way to get the data, sum the fields I need and return them into Json ?

Is this what you’re looking for?

var orders = ordersList.ToList().Select(x => new BestsellerModel
{
    ProductName = x.OrderItems.First().Product.Name,
    TotalQuantityInt = x.OrderItems.Sum(oi => oi.Quantity),
    TotalAmount = _priceFormatter.FormatPrice(x.OrderItems.Sum(oi => oi.UnitPriceInclTax), true, false) 
}).OrderByDescending(o => o.TotalQuantityInt);

Thanks for you reply.

It’s close but, doing this will sum everything and not for that product only
Screenshot_1

For example this customer would of ordered 4 Apple Icam at 1300$ each (Just test data) but instead it shows all the order items quantity and total price for that order.

Oh, then I misunderstood what’s in ordersList. I think you need to select all OrderItems first, then group them by the product, and only then create BestsellerModels out of them.

1 Like

Thanks for your suggestion. I was able to work around what I had and achieve what I was looking for.

.NET Foundation Website | Blog | Projects | Code of Conduct