0

I have been reading about jagged (an array of arrays) in several posts including this one.

I am reading a .csv file into memory. My question is do I have to know the number of rows in the .csv file in advance, or can I just assign a new row to the array?

I think this is not possible, based on looking at people's examples.

My current code (below) works just fine. I am just wondering if there is a way to insert new arrays without first counting the number of rows.

public int map_csv()
{
    // cmn 4/26/2016 Don't even bother to try anything with an empty string.

if (0 == m_ret_code)
{
    try
    {
        using (TextFieldParser parser = new TextFieldParser(m_csv_path))
        {
            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(",");

            m_row_count = 0;

            while (!parser.EndOfData)
            {
                string[] fields = parser.ReadFields();
                m_row_count++;
            }
        }

        m_csv_array = new string[m_row_count][];
        m_row_idx = 0;

        using (TextFieldParser parser = new TextFieldParser(m_csv_path))
        {
            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(",");

            if (!parser.EndOfData)
            {
                m_column_headings = parser.ReadFields();
                m_csv_array[m_row_idx] = new string[m_column_headings.Length];
                m_csv_array[m_row_idx] = m_column_headings;
                m_row_idx++;
            }

            while (!parser.EndOfData)
            {
                string[] fields = parser.ReadFields();
                m_csv_array[m_row_idx] = new string[fields.Length];
                m_csv_array[m_row_idx] = fields;
            }
        }
    }
    catch (Exception e)
    {
        m_exception_msg = e.Message;
        m_ret_code = 1;
    }
}
Community
  • 1
  • 1
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131

2 Answers2

4

Use a List<string[]> instead of an array as the "outer" collection, so you can use its Add method to assign a new string[] to a new row.

df_
  • 149
  • 4
  • 11
3

What you need a List<string[]>. You can keep adding string[] without having to worry have its size.


Or, if you decide to keep your string[][], you can just read the content of the file and split it yourself :

m_csv_array = File.ReadAllLines(m_csv_path)
    .Select(x => x.Split(',').ToArray())
    .ToArray()
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44