[英]Calculate Running Total in 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();
終於,我明白了你的問題:
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;}
}
這顯示了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;}
}
這是從這里得出的答案中得出的。 正如注釋中提到的那樣,您應該注意不要使執行多次發生,因為余額值會關閉。 使用ToList()應該注意這一點。
更簡單的解決方案:
var result=accountVouchers.Select((x, i) => new AccountVoucher { Debit = x.Debit, Credit = x.Credit, Balance = list.Take(i+1).Sum(y => y.Debit - y.Credit) });
完整的代碼:
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var accountVouchers= new List<AccountVoucher>
{
new AccountVoucher{ Debit=125, Credit=0},
new AccountVoucher{ Debit=236,Credit=0},
new AccountVoucher{ Debit=0, Credit=100},
};
var result=accountVouchers.Select((x, i) => new AccountVoucher { Debit = x.Debit, Credit = x.Credit, Balance = list.Take(i+1).Sum(y => y.Debit - y.Credit) });
}
}
class AccountVoucher
{
public int Debit { get; set; }
public int Credit { get; set; }
public int Balance { get; set; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.