C#Linq方法计算余额

时间:2017-07-19 12:58:19

标签: c# linq

我有一个这样的交易模型实体:

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()是否是计算余额的最佳方法。我只想平衡每笔交易。

2 个答案:

答案 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++;
}