【问题标题】:Streamreader to 2d arrayStreamreader 到二维数组
【发布时间】:2017-04-12 20:14:18
【问题描述】:

如何使用 Streamreader 获取文件的内容并将其放置在二维数组中。 文件如下:

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

到目前为止,我的代码如下:

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

             line = reader2.ReadLine();
        }


    }

【问题讨论】:

  • 您是否特别需要二维数组或者您可以使用更好的场景?例如一个列表。
  • 场景。所以我需要一些可以将文件内容存储在元素中的东西,由“,”分隔。所以将来我可以选择 X1,Y1(橙色)。

标签: c# arrays multidimensional-array streamreader


【解决方案1】:

我认为您尝试做的更好的方法是将您的拆分字符串放入List<string[]>。处理里面的数据会容易得多。我不认为二维数组是正确的方法。看这个例子:

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

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

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

然后您可以根据需要遍历List&lt;string[]&gt;

【讨论】:

    【解决方案2】:

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

    //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"
    

    【讨论】:

    • 感谢您的帮助。但是,如果它们的数量不同,我将如何访问 Y 坐标中的值,例如类型 1 可能有四种食物,类型 3 可能有 1 种食物。我将如何使用循环来做到这一点?任何帮助表示赞赏
    猜你喜欢
    • 1970-01-01
    • 2011-07-23
    • 2013-11-23
    • 1970-01-01
    • 2018-07-17
    • 2021-12-31
    • 2011-04-13
    • 2011-01-10
    • 2019-08-17
    相关资源
    最近更新 更多