나는 다음과 같은 코드가 있습니다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, DEF 50.0
, 60.0
GHI를, 70.0
for를 사용하여 반복하면서 abc의 numberOfItems는 2, 1은 def, 1은 ghi에 대해 사용해야합니다. abc의 totalAmount는 def의 경우 100.0, def의 경우 60.0, ghi의 경우 70.0이어야합니다. 순서는 abc의 경우 1, def의 경우 2, ghi의 경우 3입니다.
for 루프를 실행할 때주의해야 할 점은 첫 번째 테이블에서 여러 행을 건너 뛰고 있다는 것입니다. 따라서 else에 두 번째 테이블을 만들 때 numberOfItems 및 totalAmount는 여전히 0입니다. 두 번째 테이블은 어떤 같은
ABC, 100, 2, DEF 1
, 60, 1, 2
GHI, 70 (1), CSV 값의 마지막 숫자는 순서와 개수 3
바로 전에 계정 당 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 루프를 사용하지 않는 것이 어떻습니까? –
@TimSchmelter - 그것에 대해 생각했습니다. 어떻게 그걸 할 수 있니? 답변을 제공해 주시겠습니까? – Xaisoft