1
        public List<string[]> parseCSV(string path)
    {
        List<string[]> parsedData = new List<string[]>();

        try
        {
            using (StreamReader readFile = new StreamReader(path))
            {
                string line;
                string[] row;
                while ((line = readFile.ReadLine()) != null)
                {
                    row = line.Split(',');
                    parsedData.Add(row);
                }
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }

        return parsedData;
    }

I want to use this code to parse a CSV, and this returns a List filled with arrays. My question is how do I iterate through the arrays within the list if they are of unknown size?

for example:

for (int a=0; a<=CSVList(firstindex).Length;a++)
         for (int a=0; a<=CSVList(secondindex).Length;a++)

Something like this would read the first index of the CSVList and then the first array element in it...I think I am just really stuck on the syntax.

Thank you

0

4 Answers 4

5

You can use LINQ to flatten this out, if you just want to write out each value:

var results = parseCSV(path);

foreach(var str in results.SelectMany(i => i))
{
    Console.WriteLine(str);
}

Otherwise, you can do this in two loops:

var results = parseCSV(path);
foreach(var arr in results)
{
    for (int i=0;i<arr.Length;++i) // Loop through array
    {
        string value = arr[i]; // This is the array element...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

If it's just a List<string[]> values then the simplest syntax is nested foreach loops.

foreach (var arrayElement in CSVList) {
  foreach (var current in arrayElement) {
    ...
  }
}

Comments

1

You'd be much better off using foreach loops, rather than classical for loops.

With foreach your iteration is written:

foreach(string[] array in parsedData) {
    foreach(string element in array) {
        Console.WriteLine(element);
    }
}

With foreach you just say “iterate over all the elements”, you need not worry about how many elments there are.

Comments

0

Each array will have a size because all arrays in .NET inherit from System.Array. Simply reference the array based on the list index and then you can simply iterate to MyArrayOfInterest.count-1

1 Comment

Right, my question is more the syntax of c# and iterating through a list of arrays

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.