2014-10-28 76 views
0

我是lambda表達式的新手。我試圖使用.Sum()方法來查找數據庫的結果,我想總結Importe列中的所有值,我使用另一個表中的ID來選擇值,但是Json會將整個列出每個值,但它沒有完成總和。或者,我可能不知道如何應用它?。lambda表達式中的.Sum()

謝謝

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

您能否提供一些樣本數據的預期輸出數據?你爲什麼用'Importe'分組?當然,你不需要所有具有特定值的'Importe'值?你最後做了一個'ToList()',但是你抱怨說它發回了一個完整的列表。基於這段代碼片段,我們很難知道你真正想要什麼。 – StriplingWarrior 2014-10-28 18:38:19

回答

1

一位朋友幫我解決了這個問題,一個加入就是答案。我想我沒有足夠清楚地解釋我的問題,我試圖做到這一點,但採用更像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); 
0

當您使用select new { Total: sumaTotal },這不只是發回INT,這是送你的對象帶有總計字段的匿名類型。我不認爲這就是你要追求的。

,我認爲你應該做的是這樣的:

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();