Member 13787083 Ответов: 1

CSV файл в двумерный массив


Новичок C# программист здесь (3 месяца)

Мой CSV файл выглядит следующим образом:
0,1,2,3
4,5,6,7
8,9,10,11
12,13,14,15
16,17,18,19
20,21,22,23

Как мне закодировать это в 2D-массив?

Что я уже пробовал:

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);

1 Ответов

Рейтинг:
7

George Swan

Я думаю, что то, что вам может понадобиться здесь, - это зубчатый массив. Зубчатый массив-это массив массивов.


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