Click here to Skip to main content
15,217,205 members
Rate this:
Please Sign up or sign in to vote.
See more:
Newbie C# programmer here (3 months)

My CSV file looks like this:

How do I code this into a 2D array?

What I have tried:

StreamReader stream = null;
  string line;
  string[] fields;

  // open the file for reading; assumes file exists
  stream = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read));
  while (!stream.EndOfStream) // while there is still data in the file
      line = stream.ReadLine(); // read next line with product data
      part = line.Split(','); // split into fields using comma as delimiter

      for (int i = 0; i < part.GetLength(0); i++)
          list[i, 0] = part[i];
          for (int j = 0; j < list.GetLength(1); j++)
              list[0, i] = part[i];


Updated 19-Apr-18 19:49pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

I think that what you may need here is a jagged array. A jagged array is an array of arrays.

string fileName = @"C:\temp\myfile.txt";
string[] lines = File.ReadAllLines(fileName);
 int[][] jaggedArray = new int[lines.Length][];
 for (int i = 0; i < lines.Length; i++)
     string[] strArray = lines[i].Split(',');
     int[] intArray = Array.ConvertAll(strArray, int.Parse);
     jaggedArray[i] = intArray;
 string result = string.Join(", ", jaggedArray[0]);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100