Search code examples
c#logic

How to do a + (sum) operation on a list by grouping


I'm trying to add up the totals by category, but I'm not getting the right result in page cshtml.

I tried:

 <span style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important ; font-size: 18px !important ; color: #4CAF50 !important ; font-weight: 700 !important ; float: right !important">
                                Total:
                                <span style="color: #212121 !important">
                                    @{

                                        var agrupamentoPorCategoria = Model.itens.GroupBy(c => c.idCategoria);
                                        string totalPorCategoria = "";

                                        foreach (var itensPorCategoria in agrupamentoPorCategoria)
                                        {
                                            totalPorCategoria = itensPorCategoria.Sum(s => s.vSubTotal).ToString("N2");
                                        }

                                        //var totalPorCategoria = Model.itens.Sum(s => s.vSubTotal);
                                    }

                                    @totalPorCategoria
                                </span>
</span>

enter image description here

The expected result is to sum up the subtotal column by grouping the category.

In the example above the image the value would have to be 5,557.55


Solution

  • You need to select all items and then perform the sum. This should work:

    var totalPorCategoria = Model.itens.Where(c => c.idCategoria == currentId).Sum(s => s.vSubTotal);