2014-09-04 176 views
0

我正在计算我的两列的余额。我尝试了很多方法,但没有运气。计算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(); 
+0

你是什么意思大约'Caculate balance'?你只是展示你想要的结果 – 2014-09-04 06:44:28

+0

你想做什么?运行总数?或者你是否需要更新记录? – flindeberg 2014-09-04 07:14:26

回答

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()应该注意这一点。

+4

虽然这个链接可能回答这个问题,但最好在这里包含答案的重要部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 – jww 2014-09-04 07:12:11

+0

感谢您的反馈jww,我更新了我的答案以包含代码示例。 – 2014-09-04 07:26:20

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