Streamreader到2D数组 [英] Streamreader to 2d array

查看:43
本文介绍了Streamreader到2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Streamreader获取文件的内容并将其放置在2d数组中.该文件如下:

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


    }

推荐答案

您不应创建这样的静态数组,而应使用可以根据需要增长的 List .

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"

这篇关于Streamreader到2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆