2016-04-15 50 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,是的,你是对的,现在纠正。 –