我有以下代码:
int sequence = 1; //This is incremented every time the Account changes
int numberOfItems; //This is reset after the Account changes
decimal totalAmount = 0m; //This is reset after the Account changes
string prevRow; //not sure how to handle this
foreach(DataRow row in dt.Rows)
{
//I am stuck here
if(row["Account"]) == prevRow)
{
numberOfItems++;
totalAmount += Convert.ToDecimal(row["TotalAmount"]);
}
else
{
//reset everything and increase sequence
numberOfItems = 0;
totalAmount = 0m;
sequence++
}
}
我的初始表可能包含数据:
abc, 50.0
abc, 50.0
def, 60.0
ghi, 70.0
当循环使用 for 时,abc 的 numberOfItems 应该 = 2,def 为 1,ghi 为 1。abc 的总金额应为 100.0,def 为 60.0,ghi 为 70.0。abc 应该是 1,def 应该是 2,ghi 应该是 3。
运行 for 循环时我注意到的第一件事是它跳过了第一个表中的一堆行,所以当我在 else 中创建第二个表时,numberOfItems 和 totalAmount 仍然为 0。第二个表应该类似于:
abc, 100, 2, 1
def, 60, 1, 2
ghi, 70, 1, 3
其中 csv 值中的最后一个数字是序列,之前的数字是每个帐户的 numberOfItems。
for (int i = 0; i < dt.Rows.Count; i++ )
{
DataRow row = dt.Rows[i];
DataRow prevRow = i > 0 ? dt.Rows[i - 1] : null;
if (prevRow != null && row[1] == prevRow[1])
{
numberOfItems++;
totalAmount += Convert.ToDecimal(row[2]);
row[3] = "D";
row[4] = c;
row[5] = sequence;
}
else
{
dt2.Rows.Add("N",
c,
row[1],
row[2],
row[3],
numberOfItems,
totalAmount,
sequence);
numberOfItems = 0;
totalAmount = 0m;
sequence++;
}
}