Patrigon
Patrigon

Reputation: 157

Checking the size of a list of arrays

I have a list of string arrays:

List<string[]> parsedRaw = new List<string[]>();

This list contains lines read in from a CSV, where parsedRaw[3][5] would be the fifth item read off the third line of the CSV.

I know that I can find the number of rows in the list with:

parsedRaw.Count

But, given a row, how can I find the number of elements in that row? I'm trying to implement a test before entering a loop to read from the list, in order to avoid an "Index was outside the bounds of the array" error, where the loop is:

for (k = 0; k < nBytes; k++)
{
    TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}

I'm encountering the error on a row in the CSV that has fewer elements than the others. Before entering this loop, I need to check whether parsedRaw[i] has at least "StartInt + nBytes" elements.

Thanks for any suggestions!

Upvotes: 3

Views: 4124

Answers (3)

JaredPar
JaredPar

Reputation: 755387

The number of elements in a given row is determined by

parsedRaw[theRowIndex].Length

To fix your for loop you need to constrain the StartInt + k value to be less than the minimum of nBytes and the row length

for (k = 0; (k < nBytes) && (k + StartInt < parsedRaw[i].Length); k++)
{
    TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}

Upvotes: 3

Firoz Ansari
Firoz Ansari

Reputation: 2515

Try

List<string[]> parsedRaw = new List<string[]>();
parsedRaw.Add(new string[] {"test1", "test2"});
parsedRaw.Add(new string[] { "test1", "test2", "test3" });
int totalSize = 0;
for (int i = 0; i < parsedRaw.Count(); i++)
{
    int rowSize = 0;
    for (int k = 0; k < parsedRaw[i].Count(); k++)
    {
        rowSize += parsedRaw[i][k].Length;    
    }                
    totalSize += rowSize;
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

A row is just a string array string[], so you can find its size using the Length property of the array.

foreach (string[] row in parsedRaw) {
    for (int i = 0 ; i != row.Length ; i++) {
        // do something with row[i]
    }
}

Upvotes: 6

Related Questions