Iterating through a List that is filled with arrays in C#
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开发者_JS百科; 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
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...
}
}
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) {
...
}
}
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.
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
精彩评论