Search code examples
c#linqlambdalinq-expressions

.Sum() in lambda expressions


I'm new to lambda expressions. I'm trying to use the .Sum() method to a result from a db search, I want to sum all the values from the Importe column, I'm selecting the values using an ID from another table, but the Json send me back the entire list with every value, it's not doing the sum. Or maybe I don't know how to apply it?

Thank you

public JsonResult IngresaCuentas(string codigo)
{
    ContextoAngeles db = new ContextoAngeles();

    var suma = (from data in db.Cuentas
                where data.Codigo == codigo
                select (from n in db.MovimientosPolizas
                        where data.Id == n.IdCuenta
                        group n by new { n.Importe} into g
                        let sumaTotal = (g.Sum(n => n.Importe))
                        select new
                        {
                            Total: sumaTotal
                        })).ToList();

        return Json(suma, JsonRequestBehavior.AllowGet);
}

I'm getting this in the Console:

[[{"Total":0},{"Total":20},{"Total":150},{"Total":330},{"Total":56.2},{"Total":240},{"Total":1750},{"Total":70.07},{"Total":480},{"Total":540},{"Total":95},{"Total":200},{"Total":108},{"Total":108.8},{"Total":880},{"Total":111.98},{"Total":115},{"Total":240},{"Total":125},{"Total":129.98},{"Total":780},{"Total":131.42},{"Total":134.59},{"Total":1260},{"Total":141.65},{"Total":145}]] (and a lot more..)

Solution

  • A friend helped me to resolve this issue and a Join was the answer. I think i didn't explain my problem clear enough, I was trying to do that but in a different way more like SQL syntax, if anyone knows a good place to learn about lambda expressions would be great.

    Thank all of you! Here the solution.

     var dato = db.Cuentas.Where(x => x.Codigo == codigo)
                    .Join(db.MovimientosPolizas, cuentas => cuentas.Id, movimientos => movimientos.IdCuenta, (cuenta, movimiento) => new { sumImporte = movimiento.Importe, cuenta = cuenta.Nombre })
                    .Sum(x => x.sumImporte);