我有以下代碼:如何檢查使用foreach時DataTable行是否發生了變化?
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++;
}
}
'foreach'不知道它是前一行。那麼你爲什麼不簡單地使用'for-loop'呢? –
@TimSchmelter - 我想過這個。我會怎麼做呢?你介意提供一個答案嗎? – Xaisoft