Click here to Skip to main content
15,884,237 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Newbie C# programmer here (3 months)

My CSV file looks like this:
0,1,2,3
4,5,6,7
8,9,10,11
12,13,14,15
16,17,18,19
20,21,22,23

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];
          }

      }

      lst.Items.Add(list);
Posted
Updated 8-May-22 12:53pm
v2

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


C#
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]);
 Console.WriteLine(result);//0,1,2,3
 
Share this answer
 
//read the .csv file and store it in a list of string values
    var DataReader = new BufferedReader(new FileReader(csvPath.toString()));
    String line;
    var Arr = new ArrayList<String>();
    while ((line = DataReader.readLine()) != null) {
        Arr.add(line);
    }

    //break each item in the list to a matrix 
    var TwoDimdata = new String[Arr.size()][Arr.get(0).toString().split(",").length];
    for (var i = 0; i < TwoDimdata.length; i++) {
        for (var j = 0; j < TwoDimdata[0].length; j++) {
            var arr = Arr.get(i).split(",");
            TwoDimdata[i][j] = arr[j];
        }
    }
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900