2016-01-28 91 views
1

我似乎無法讓我的csv文件將數據存儲到2D數組中。從windows窗體應用程序的CSV文件中讀取數據並將其存儲到2D數組中

這就是我的代碼看起來像至今:

try 
{ 
    string nrValues; 
    fs = new FileStream(path, FileMode.Open, FileAccess.Read); // open for reading 
    // the file has opened; can read it now 
    sr = new StreamReader(fs); 

    while (!sr.EndOfStream) 
    { 
     line = sr.ReadLine(); 
     parts = line.Split(','); 
     for (int i = 0; i < sizes.Length; i++) 
     { 
      textiles[nrValues, i] = parts[i]; 
     } 

     nrValues++; 
    } 

這是我的CSV文件看起來像:

csv

+2

什麼是'大小'? – Jaco

+1

您還將'nrValues'定義爲一個字符串而不是int,這會導致編譯錯誤,至少對於nrValues ++來說。 – Jaco

回答

0

你應該能夠用代碼片段來讀取數據下面。我已將nrValues更改爲整數,因爲您未包含sizes的定義,所以我使用parts.Length而不是sizes.Length。但是,請看這個答案最後的改進版本。使用LINQ,你可以在兩行中實現相同的代碼。

using System.IO; 

namespace ConsoleApplication23 
{ 
    internal class Program 
    { 
     private static void Main(string[] args) 
     { 
      int nrValues=0; 
      FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); // open for reading 
      // the file has opened; can read it now 
      StreamReader sr = new StreamReader(fs); 

      string[,] textiles = new string[6, 4]; 

      while (!sr.EndOfStream) 
      { 
       string line = sr.ReadLine(); 
       string[] parts = line.Split(','); 

       for (int i = 0; i < parts.Length; i++) 
       { 
        textiles[nrValues, i] = parts[i]; 
       } 
       nrValues++; 
      } 
     } 
    } 
} 

然而,更加簡潔和更短的,你可以,如果你是幸福的編寫使用LINQ相同的代碼,結果是交錯數組,而不是一個二維數組:

var lines = File.ReadAllLines(path); 
var textiles = lines.Select(line => line.Split(',')).ToArray(); 
+0

由於其中一個問題實際上是變量類型,因此在代碼段中聲明類型而不是使用'var'會更有幫助嗎? – Ciara

+0

@Ciara,我已更新帖子以明確定義類型。使用var有點專業懶惰:-)我同意,在這種情況下,最好明確定義類型。 – Jaco

相關問題