2016-04-15 91 views
0

當我運行時,我只能得到Month.txt文件的內容,我明白這只是因爲我已經將它設置爲foreach中的字符串,但是我無法弄清楚如何添加其他文件到這個以及我得到的所有文件的內容,而不僅僅是本月?foreach讀取多個數組

string[] month = System.IO.File.ReadAllLines 
      (@"E:\project1\input\Month.txt"); 

      string[] 1_AF = System.IO.File.ReadAllLines 
      (@"E:\project1\input\1_AF.txt"); 

      string[] 1_Rain = System.IO.File.ReadAllLines 
      (@"E:\project1\input\1_Rain.txt"); 

      string[] 1_Sun = System.IO.File.ReadAllLines 
      (@"E:\project1\input\1_Sun.txt"); 

      string[] 1_TBig = System.IO.File.ReadAllLines 
      (@"E:\project1\input\1_TBig.txt"); 

      string[] 1_TSmall = System.IO.File.ReadAllLines 
      (@"E:\project1\input\1_TSmall.txt"); 

      System.Console.WriteLine("Contents of all files =:"); 
      foreach (string months in month) 
      { 
       Console.WriteLine(months + "\t" + 1_AF + "\t" + 1_Rain + "\t" + 1_Sun + "\t" + 1_TBig + "\t" + 1_TSmall); 
      } 
      Console.ReadKey(); 
+0

你必須創建數組列表並添加單個文件的內容放到這個名單,那麼你可以申請的foreach爲數組 –

+0

你有沒有考慮使用'List','Dictionary',或'Tuple'?它們對於像您的情況非常有用。 – Ian

回答

2

foreach loop爲給定的集合提供了一個迭代器。如果您需要多個集合的數據,那麼您需要多個迭代器。

如果所有的數組大小都一樣的,你可以隨時使用傳統for迴路,並使用數字索引來訪問數組位置:

for (int i = 0; i < month.length; i++) 
{ 
    Console.WriteLine(month[i]+ "\t" + 1_AF[i] + "\t" + 1_Rain[i] + "\t" + 1_Sun[i] + "\t" + 1_TBig[i] + "\t" + 1_TSmall[i]); 
} 
0
using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.IO; 

namespace SOFAcrobatics 
{ 
    public static class Launcher 
    { 
     public static void Main (String [] paths) 
     { 
      List<String> pool = new List<String>(); 
      foreach (String path in paths) 
      { 
       pool.AddRange(File.ReadAllLines(path)); 
      } 
      // pool is now populated with all the lines of the files given from paths 
     } 
    } 
} 
0

以下解決方案將工作即使你有不同大小的數組。如果所有數組的大小相同,則可以始終使用單個迭代器。

static void Main(string[] args) 
    { 
     string[] a = System.IO.File.ReadAllLines 
     (@"E:\test\a.txt"); 

     string[] b = System.IO.File.ReadAllLines 
     (@"E:\test\b.txt"); 

     string[] c= System.IO.File.ReadAllLines 
     (@"E:\test\c.txt"); 

     System.Console.WriteLine("Contents of all files =:"); 
     for (int x = 0, y = 0, z = 0; x < a.Length || y < b.Length || z < c.Length; x++,y++,z++) 
     { 
      string first = string.Empty, second = string.Empty, third = string.Empty; 

      if (x < a.Length) 
       first = a[x]; 
      if (y < b.Length) 
       second = b[y]; 
      if (z < c.Length) 
       third = c[z]; 

      Console.WriteLine("\t" + first + "\t" + second + "\t" + third); 
     } 
     Console.ReadKey(); 
    } 
+0

'third = c [y];'在這裏不是'z'嗎? –

+0

@ FeDe,是的,你是對的,現在糾正。 –