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

  • 本文关键字:求和 Linq 使用 c# linq
  • 更新时间 :
  • 英文 :


我只需要返回一个结果,我需要将所有状态(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

如何提问:

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

你试过了吗

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

另一种方式是:

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

相关内容

  • 没有找到相关文章

最新更新