使用Linq C#进行求和和减法

时间:2015-06-10 22:21:01

标签: c# linq

我只需要返回一个结果,我需要将所有状态500.html(1, 3)相加,然后减去每个结果:

(2, 4, 5)

我试过:

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

2 个答案:

答案 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;
    });

答案 1 :(得分: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"));