我有一个这样的交易模型实体:
public class TransactionModel
{
public int Id { get; set; }
public int? Withdraw { get; set; }
public int? Deposit { get; set; }
public DateTime Date { get; set; }
}
我使用TransactionViewModel
类在视图中显示只有一个属性超过TransactionModel
类且Balance
我希望在显示每笔交易时显示余额。
Withdraw Deposit Balance
1) - 100 100
2) 50 - 50
3) 10 - 40
我使用linq Select
方法,但当我想计算余额时,我无法使用Sum()
方法。
public IEnumerable<TransactionViewModel>
CreateTransactionViewModel(IEnumerable<TransactionModel> transactions)
{
return transactions.Select(x => new TransactionViewModel
{
Id= x.Id,
Date = x.Date,
Deposit = x.Deposit,
Withdraw = x.Withdraw,
Balance = //...
});
}
更新
我不确定使用Sum()
是否是计算余额的最佳方法。我只想平衡每笔交易。
答案 0 :(得分:1)
你可以像这样计算:
return transactions.Select(x => new TransactionViewModel
{
Id= x.Id,
Date = x.Date,
Deposit = x.Deposit,
Withdraw = x.Withdraw,
Balance = transactions.Where(y => y.Id <= x.Id).Sum(z => z.Deposit ?? 0 - z.Withdraw ?? 0)
});
答案 1 :(得分:1)
为什么要使用Linq?你可以通过一个简单的循环来完成这个。
int balance = 0;
int row = 1;
List<BalanceModel> result = new List<BalanceModel>();
foreach(TransactionModel tm in list)
{
balance += tm.Deposit - tm.Withdraw;
BalanceModel bm = new BalanceModel()
{
Row = row,
Withdraw = tm.Withdraw,
Deposit = tm.Deposit,
Balance = balance,
};
result.Add(bm);
row++;
}