2011-10-01 53 views
1

我有幾個電話號碼,我的文件是這樣的:儲存號碼的文件轉換成二維數組

22 33 44 55 
11 45 23 14 
54 65 87 98 

,我想救他們(我分裂後)在二維數組,如:

x[0][1]==33 

我該怎麼做?

編輯:

我寫它的某些部分,我把註釋代碼:

StreamReader sr = new StreamReader(@"C:\Users\arash\Desktop\1.txt"); 
     string[] strr; 
     List<List<int>> table = new List<List<int>>(); 
     List<int> row = new List<int>(); 
     string str; 
     while ((str = sr.ReadLine()) != null) 
     { 
      strr = str.Split(' ');//here how should i save split output in two dimension array?? 

      } 

TIA

回答

2

一個這樣做的方式可以是這樣的:

StreamReader sr = new StreamReader(@"C:\Users\arash\Desktop\1.txt"); 
List<int[]> table = new List<int[]>(); 
string line; 
string[] split; 
int[] row; 
while ((line = sr.ReadLine()) != null) { 
    split = line.Split(' '); 
    row = new int[split.Count]; 
    for (int x = 0; x < split.Count; x++) { 
     row[x] = Convert.ToInt32(split[x]); 
    } 
    table.Add(row); 
} 

表就可以這樣來訪問:

table[y][x] 
+0

'for' co使用LINQ可以更清晰地編寫。 – svick

1

通過使用嵌套的循環,你可以輕鬆地創建多維數組。

嵌套兩個循環,外部遍歷輸入中的行,內部遍歷行中的數字。

或者您可以在LINQ

var myArray = File.ReadAllLines(@"C:\Users\arash\Desktop\1.txt") 
    .Where(s=> !string.IsNullOrWhiteSpace(s)) 
    .Select(l => l.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries) 
     .Select(n => Convert.ToInt32(n)).ToArray()).ToArray(); 

myArray[0][1]給你33