I have a for
loop implementation for merging documents and page re-numbering. But since I am modifying the collection while iterating, I suspect that the code might break. As foreach
doesn't allow collection modification, I have implemented it with for
.
Is there any better way to implement/optimize this part of code? Also, is it possible to reduce these 3 loops to a single one?
// Merge Document Sequence
for (int k = 0; k < response.documents.Count; k++)
{
string presentDocument = string.Empty;
string laterDocument = string.Empty;
presentDocument = response.documents[k].docType;
if ((response.documents.Count - 1) != k)
laterDocument = response.documents[k + 1].docType;
if ((laterDocument == presentDocument))
{
response.documents[k].pages.AddRange(response.documents[k + 1].pages);
response.documents.RemoveAt(k + 1);
k = k - 1;
}
}
// Page Re-numbering
for (int i = 0; i < response.documents.Count; i++)
{
for (int j = 0; j < response.documents[i].pages.Count; j++)
response.documents[i].pages[j].pageNo= j + 1;
}