0

How do I take the contents of a file using a Streamreader and place it in a 2d array. The file is as follows:

    type1,apple,olive,pear
    type2,orange,nuts,melon
    type3,honey,grapes,coconut

So far my code is as follows:

     public static void invent()
    {
        StreamReader reader2 = new StreamReader("food.txt");
        while (reader2.EndOfStream == false)
        {
            string[,] line = new string[1000, 1000];

             line = reader2.ReadLine();
        }


    }
xxish
  • 49
  • 9
  • do you speciffically need a 2d array or you can work with a better scenario?. A List for example. – NicoRiff Apr 12 '17 at 20:20
  • scenario. so i need something where it can store the content of the file in elements , separated by the ",". So in future i can select X1,Y1 (orange). – xxish Apr 12 '17 at 20:26
  • Possible duplicate of [Create ArrayList from array](http://stackoverflow.com/questions/157944/create-arraylist-from-array) – xxish Apr 20 '17 at 13:46

2 Answers2

0

I think the better approach for what you are trying to do is to have your splitted string into a List<string[]>. It would be much more easier to work with the data inside. I do not think two dimension array is the right approach. Look at this example:

List<string[]> splittedList = new List<string[]>();

string[] list = File.ReadAllLines("c:/yourPath.txt");

foreach (string s in list)
{
    splittedList.Add(s.Split(','));
}

Then you can iterate through the List<string[]> as you need.

NicoRiff
  • 4,803
  • 3
  • 25
  • 54
0

You shouldn't create a static array like that, you should use a List that can grow as needed.

//Read the lines
string[] lines = System.IO.File.ReadAllLines(@"food.txt");

//Create the list
List<string[]> grid = new List<string[]>();

//Populate the list
foreach (var line in lines) grid.Add(line.Split(','));

//You can still access it like your 2D array:
Console.WriteLine(grid[1][1]); //prints "orange"
Tee
  • 414
  • 2
  • 8
  • 19
  • Thanks for the help. But how would I access the in the Y co ordinate if they were different amounts for example type 1 may have four food items and type 3 may have 1 item. how would i do this using a loop? any help is appreciated – xxish Apr 29 '17 at 12:52