2013-02-22 40 views
1

文本文件我目前有这样的:C#读从由逗号分隔成2D阵列

using (StreamReader sr = new StreamReader("answers.txt")) 
{ 
    for (iCountLine = 0; iCountLine < 10; iCountLine++) 
    { 
     for (iCountAnswer = 0; iCountAnswer < 4; iCountAnswer++) 
     { 
      sQuestionAnswers[iCountLine, iCountAnswer] = 
     } 
    } 
} 

我的文本文件的格式是这样的(10行文字,用4项上以逗号分隔的每一行):

example, example, example, example 
123, 123, 123, 123 

我不知道我以后需要“=”,在for循环得到它的阅读和文本文件的内容分成了二维数组。

回答

2

我不知道我以后需要 “=”,在for循环

还有一条线上面丢失:

var tokens = sr.ReadLine().Split(','); 

现在行与=看起来是这样的:

sQuestionAnswers[iCountLine, iCountAnswer] = tokens[iCountAnswer]; 
+0

非常感谢! – SexySaxMan 2013-02-22 13:57:50

0
string line; 

using (var sr = new StreamReader("answers.txt")) 
{ 
    while ((line = sr.ReadLine()) != null) 
    { 
     for (int iCountLine = 0; iCountLine < 10; iCountLine++) 
     { 
      var answers = line.Split(','); 
      for (int iCountAnswer = 0; iCountAnswer < 4; iCountAnswer++) 
      { 
       sQuestionAnswers[iCountLine, iCountAnswer] = answers[iCountAnswer]; 
      } 
     } 
    } 
} 
0

我建议你改变方法。

使用StreamReader类的ReadLine()方法遍历文件。 然后使用拆分(new [] {','})拆分读取行,这会给你每一条记录。 最后,sQuestionAnswers [iCountLine,iCountAnswer]将是:Split数组的[iCountAnswer]记录。

2

这不使用StreamReader,但它的短,很容易理解:

 string[] lines = File.ReadAllLines(@"Data.txt"); 
     string[][] jaggedArray = lines.Select(line => line.Split(',').ToArray()).ToArray(); 

行由ReadAllLines根据新行提取。通过在每行上调用Split来提取列值。它返回可以类似地用于多维数组的锯齿状数组,也是锯齿状数组通常比多维数组快。