在 DataTable 列中动态计算和添加值 - ASP.Net C#

Dynamically Calculate & Add value in a DataTable Column - ASP.Net C#

我有一个从数据库绑定的数据表,其列为:Id、Date、Credit、Debit。

我想添加新列 "Balance" 并且它的值应该通过公式计算每一行; [上一行余额] - [贷方] + [借方]

我做过这样的事情:

dt; //Filled & having columns ID, Date, Debit, Credit
dt.Columns.Add("Balance");

foreach(DataRow row in dt.Rows)
{
    //What should I do here to apply above formula
}

我想您希望第一行的公式为 Credit + Debit,因为没有前一行,并调整您为任何其他行编写的公式。如果是这样,这将是安全的方法:

for (int i = 0; i < dt.Rows.Count; i++)
{
    DataRow row = dt.Rows[i];

    decimal credit = 0, debit = 0, previousBalance = 0;
    decimal.TryParse(row["Credit"].ToString(), out credit);
    decimal.TryParse(row["Debit"].ToString(), out debit);

    if (i > 0)
        decimal.TryParse(dt.Rows[i-1]["Balance"].ToString(), out previousBalance);

    row["Balance"] = i == 0 ? credit + debit : previousBalance - credit + debit;
}