I have the following code that loops through a DataTable and builds another one if certain conditions are met. However, the last row in the initial DataTable is being skipped.
for (int i = 0; i < dt.Rows.Count; i++ )
{
DataRow row = dt.Rows[i];
DataRow nextRow = i < dt.Rows.Count - 1 ? dt.Rows[i + 1] : null;
string account = row[1].ToString();
string nextAccount = "";
if (nextRow != null)
{
nextAccount = nextRow[1].ToString();
}
numberOfItems++;
totalAmount += Convert.ToDecimal(row[2]);
row[4] = "D";
row[5] = c;
row[6] = Sequence;
if (nextRow != null && i < dt.Rows.Count && account != nextAccount)
{
dt2.Rows.Add("N",
c,
row[1],
row[2],
row[3],
numberOfItems,
totalAmount,
Sequence);
numberOfItems = 0;
totalAmount = 0m;
Sequence++;
}
}
In the above code, if I have a table such as:
abc, 1, 2, 3 abc, 1, 2, 5 def, 1, 3, 6
It will process both abc’s, but not def.
dt2 should contain:
abc, 1, 2, 8, 2 def, 1, 3, 6, 1
Where 8 is the total for the 4th column in dt and 2 is the number of abc rows.
I am only getting this though
abc, 1, 2, 8, 2
The problem is with this line:
Try changing it to
I removed:
because that prevents the last record from being added.
I also removed:
because that is already enforced by your
forloop.Note: the last row still may not be added if account is the same as the previous row. Not sure what behaviour you wish here.