2

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.

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

It kinda works, however jj goes outside size and it shouldn't be bigger then size
Okay, but the range of indexes in allSheets and for get_Sheets must have the same size. Or does it make sense to have allSheets bigger than the size of the worksheet? Maybe size should be smaller? Or if you want to leave empty space at the end of allSheets, then change the loop condition to ii < size - 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.