2014-09-04 70 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;} 
}