Streamreader to 2d array

╄→尐↘猪︶ㄣ 提交于 2019-12-12 01:52:34

问题


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


    }

回答1:


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.




回答2:


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"


来源:https://stackoverflow.com/questions/43378834/streamreader-to-2d-array

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