我是lambda表达式的新手。我正在尝试将.Sum()
方法用于数据库搜索的结果,我想对Importe
列中的所有值求和,我使用ID
选择值从另一张桌子,但是Json用每个值将整个列表发回给我,它没有做总和。或者我可能不知道如何应用它?
谢谢
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);
}
我在控制台中收到了这个:
[[{"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..)
答案 0 :(得分:2)
一位朋友帮助我解决了这个问题,加入就是答案。我认为我没有清楚地解释我的问题,我试图这样做但是以不同的方式更像SQL语法,如果有人知道一个学习lambda表达的好地方会很棒。
谢谢大家!这是解决方案。
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);
答案 1 :(得分:1)
当您使用select new { Total: sumaTotal }
时,不仅仅是发送回int,而是向您发送一个带有Total字段的匿名类型的对象。我不认为这就是你要追求的目标。
我认为你应该做的是这样的事情:
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 sumaTotal)).ToList();
或者,如果您要选择的是您查询过的每个Importe
的总和:
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 sumaTotal)).Sum();