Reputation: 21
I can't find how to implement jagged array using for loop. I have tried, however only the last smaller array becomes jagged arrays item.
string[][] allSheets = new string[size][];
This is how I declare. Below is how I get allSheets[number] element.
public string[] get_Sheets(int colNum)
{
CellReference[] cr = new CellReference[rows_.Length];
ISheet sheet = wb.GetSheetAt(0);
IRow[] row = new IRow[rows_.Length];
ICell[] cell = new ICell[rows_.Length];
string[] cellResult = new string[rows_.Length];
for (int i = 0; i < cr.Length; i++)
{
cr[i] = new CellReference(rows_[i] + colNum);
row[i] = sheet.GetRow(cr[i].Row);
cell[i] = row[i].GetCell(cr[i].Col);
cellResult[i] = cell[i].ToString();
}
return cellResult;
}
My two for loops looks something like this:
for (int ii = 0; ii < size; ii++)
{
for (int jj = 2; jj < size; jj++)
{
allSheets[ii] = get_Sheets(jj);
}
}
Notice how I started jj
with 2. I had to since it's how excel files work..
You could clearly see that despite everything my every allSheets[ii]
would become the last possible j number in for loop. I had tried to swap the loops so i
starts first, however result is the same.
Upvotes: 2
Views: 160
Reputation: 112612
I think that you should use only one loop, because you are iterating only the main array here. You do not have to handle 2 dimensions on this level. The second loop (for the other dimension) is already inside get_Sheets
.
for (int ii = 0; ii < size; ii++)
{
allSheets[ii] = get_Sheets(ii + 2);
}
Note that your 2 for-loops are not executing in parallel, they are nested. The inner loop is iterating size - 2
times per each iteration of the outer loop. This means that you are getting size * (size - 2)
iterations. This not what you want.
An alternative way of doing this a lesser know feature of the for-loop. (This is probably what you intended to do with the 2 loops.)
for (int ii = 0, jj = 2; ii < size; ii++, jj++)
{
allSheets[ii] = get_Sheets(jj);
}
Upvotes: 1