私は次のコードを持っています:
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のtotalAmountは、100.0、defの場合は60.0、ghiの場合は70.0である必要があります。シーケンスは、abcの場合は1、defの場合は2、ghiの場合は3である必要があります。
forループを実行しているときに最初に気付いたのは、最初のテーブルの行の束をスキップしていることです。したがって、elseに2番目のテーブルを作成しても、numberOfItemsとtotalAmountは0のままです。2番目のテーブルは次のようになります。
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++;
}
}