2015-06-10 20 views
0

我需要返回结果只有一个,我需要总结所有状态(1, 3)(2, 4, 5)然后减去每个总示例:萨姆并减去使用LINQ C#

cashtransaction_amount, cashtransactionstatus_id 
50.00     1 (+) 
39.99     2 (-) 
330.70     3 (+) 
10.00     5 (-) 
50.50     4 (-) 
30.00     2 (-) 

Sum(1,3): 50.00 + 330.70 = 380.70 
Sum(2, 5, 4): 39.99 + 10.00 + 50.50 + 30.00 = 130.49 
Final Result Sum(1,3) - Sum(2, 5, 4): 380.70 - 130.49 = 250.21 

我tryed:

(from DataRow Transaction_DataRow in Dt_transaction.AsEnumerable() 
where Transaction_DataRow.Field<Int32>("cashpaymenttype_id") == 1 // Cash Money 
group Transaction_DataRow by Transaction_DataRow.Field<Int32>("cashtransactionstatus_id") into tmp 
select new 
    { 
     cashtransaction_amount = tmp.Sum(x => (x.Field<Int32>("cashtransactionstatus_id") == 1 || x.Field<Int32>("cashtransactionstatus_id") == 3) ? x.Field<Double>("cashtransaction_amount") : -x.Field<Double>("cashtransaction_amount")) 
    }).Aggregate(Transaction_DataTable, (dt, result) => { dt.Rows.Add(result.cashtransaction_amount); return dt; }); 

回答

1

另一种方法是:

total = tmp.Select(b => 
      { 
       var id = b.Field<Int32>("cashtransactionstatus_id"); 
       return (id == 1 || id == 3 ? 1 : -1) * 
         b.Field<Double>("cashtransaction_amount"); 
      }).Sum(); 

或者:

total = tmp.Sum(b => (new[]{1,3}.Contains(b.Field<Int32>("cashtransactionstatus_id")) 
          ? 1 : -1) * b.Field<Double>("cashtransaction_amount")); 
+0

感谢您的帮助,您可以告诉我'b' var的定义在哪里?因为我得到以下错误:'名称'b'在当前上下文中不存在' –

+0

x应该是b。固定 – SimpleVar

+0

朋友以各种方式尝试你的例子,并总是给我一个不好的结果,请给我一个完整的例子适用于我的代码?谢谢 –

2

您是否尝试过

cashtransaction_amount = tmp.Aggregate((a,b) => 
    { 
     var id = b.Field<Int32>("cashtransactionstatus_id"); 
     var amt = b.Field<Double>("cashtransaction_amount"); 
     return id == 1 || id == 3 ? a + amt : a - amt; 
    }); 
+0

不是问题,感谢 – maksymiuk

+0

海兰谢谢你的帮助,但我得到这个错误:'错误3号“+”不能应用于类型System.Data的”操作数.DataRow'和'double'' –

+0

尝试铸造id和amt像这样'int32 id = b.Field (“cashtransactionstatus_id”)as int32;''double amt = b.Field (“cashtransaction_amount”)double; – maksymiuk