Reading data from a CSV to an array of arrays (C#)

爷,独闯天下 提交于 2019-12-20 05:54:29

问题


I have the CSV file opened, but I can't figure out how to put the resultant array from splitting the line into another array. I have the following code currently, hopefully it gives more of an idea of what I'm meaning:

    private void ReadFileToArray(StreamReader file)
    {
        int i = 0;
        string[][] FP_GamesArray;
        while (!file.EndOfStream)
        {
            string line = file.ReadLine();
            if (!String.IsNullOrWhiteSpace(line))
            {
                string[] values = line.Split(',');
                MessageBox.Show(values.ToString());
                FP_GamesArray[i] = values;
            }
            i++;
        }
    }

Any ideas? I get two errors: One saying Cannot implicitly convert type 'string[]' to 'string' and second saying Use of unassigned local variable 'FP_GamesArray'.


回答1:


You need to initialize your array, to do that you need to know how many lines in there.

Instead of reading line by line you can do:

string[][] FP_GamesArray = File.ReadLines("path")
                          .Select(line => line.Split(','))
                          .ToArray();

Or altenatively, you can start with a List<string[]>, use it's add method, then convert it to an array after the reading is finished, like below:

List<string[]> lines = new List<string[]>();
while (!file.EndOfStream)
{
     string line = file.ReadLine();
     if (!String.IsNullOrWhiteSpace(line))
     {
         lines.Add(line.Split(',');   
     }
}

string[][] FP_GamesArray = lines.ToArray();



回答2:


As a supplemental answer for the means of producing a list, here is what I was able to get to work:

  List<string> rows = MyCSVString.Replace("\n", "").Split('\r').ToList();
  List<List<string>> listedMatrix = new List<List<string>>();
  foreach(var x in rows)
  {
    if(x != "")
    {
      var rowList = x.Split(',').ToList();
      listedMatrix.Add(rowList);
    }
  }
  • yea, commas will mess it up, as this isn't really true parsing.


来源:https://stackoverflow.com/questions/24516878/reading-data-from-a-csv-to-an-array-of-arrays-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!