0

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'.

2
  • 2
    An array isn't dynamic, you can't just declare it like you have and start assigning values to it You have to give it a size as well. Where are you getting the first error? Commented Jul 1, 2014 at 18:23
  • Both are tied to the FP_GamesArray[i] = values line, the first error is underlining the values code, and the second the FP_GamesArray[i] code. Commented Jul 1, 2014 at 18:27

2 Answers 2

7

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I like the List<string[]> option because a lot of people don't understand Linq.
Works a treat! Thanks a lot. I'll try the List<string[]> method for completeness in a bit...
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.