计算Linq中的运行总计

时间:2014-09-04 06:38:21

标签: c# asp.net-mvc linq

我正在尝试计算两列的余额。我尝试了很多方法。但没有运气。

例如:

我想得到这样的结果:


借记 信用 余额
===== ====== =======
125.00 0.00 125.00
236.00 0.00 361.00
0.00 100.00 261.00

我的代码

var filteredSales = (from av in db.AccountVouchers
            join l in db.Ledgers on new {LedgerID = (Int32) av.LedgerID} equals new     {LedgerID = l.LedgerID}
            join sm in db.SalesMasters on av.VoucherNo equals sm.BillNo.ToString()
            where (av.VoucherDate >= FromDate && av.VoucherDate <= ToDate && av.LedgerID == LedgerID)
            group new {av, l, sm} by new
            {
                av.VoucherDate,
                l.LedgerName,
                av.VoucherType,
                av.VoucherNo,
                sm.REFNO,
                av.Debit,
                av.Credit,
                av.Narration
            }
            into g
            select new
            {

                g.Key.VoucherDate,
                g.Key.LedgerName,
                g.Key.VoucherType,
                VoucherNo = (g.Key.VoucherType != "SALES" ? g.Key.REFNO : g.Key.VoucherNo),
                //g.Key.VoucherNo,
                g.Key.Debit,
                g.Key.Credit,
                g.Key.Narration,
                dSum = g.Sum(s => s.av.Debit),

                //Balance=g.Key.Debit-g.Key.Credit,

              //  TBal = int.Parse(TBal) + (g.Key.Debit != 0 ? TBal + g.Key.Debit : TBal - g.Key.Credit))


                             }).ToList();

2 个答案:

答案 0 :(得分:1)

最后,我理解你的问题:

void Main()
{
    var list=new List<test>
    {
      new test{ Debit=125, Credit=0},
      new test{ Debit=236,Credit=0},
      new test{ Debit=0, Credit=100},
    };
    if(list.Any())
    {
       var first = list.First();
       first.Balance = first.Debit - first.Credit;
       list.Aggregate((x,y)=>{ y.Balance = x.Balance + y.Debit - y.Credit; return y;});
    }

    list.Dump();
}
class test
{
   public int Debit {get;set;}
   public int Credit {get;set;}
   public int Balance {get;set;}
}

答案 1 :(得分:0)

这显示了Tim的另一种语法示例。

void Main()
{
    var list=new List<test>
    {
      new test{ Debit=125, Credit=0},
      new test{ Debit=236,Credit=0},
      new test{ Debit=0, Credit=100},
    };
    int balance = 0;
    list = list.Select( i=> { 
        balance += i.Debit - i.Credit;
        i.Balance = balance;
        return i;
        }).ToList();
    list.Dump();
}
class test
{
   public int Debit {get;set;}
   public int Credit {get;set;}
   public int Balance {get;set;}
}

这取自正在执行总计的答案here。正如评论中提到的那样,您应该小心,因为平衡值将关闭,您不会导致执行多次发生。使用ToList()可以解决这个问题。