foreach读取多个数组



当我运行时,我只得到Month.txt文件的内容,我知道这只是因为我已经将其设置为foreach中的字符串,但我无法计算如何将其他文件也添加到其中。我得到所有文件的内容而不仅仅是月份的内容吗?

string[] month = System.IO.File.ReadAllLines
            (@"E:project1inputMonth.txt");
            string[] 1_AF = System.IO.File.ReadAllLines
            (@"E:project1input1_AF.txt");
            string[] 1_Rain = System.IO.File.ReadAllLines
            (@"E:project1input1_Rain.txt");
            string[] 1_Sun = System.IO.File.ReadAllLines
            (@"E:project1input1_Sun.txt");
            string[] 1_TBig = System.IO.File.ReadAllLines
            (@"E:project1input1_TBig.txt");
            string[] 1_TSmall = System.IO.File.ReadAllLines
            (@"E:project1input1_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(); 

foreach循环在给定集合上提供迭代器。如果需要多个集合的数据,那么就需要多个迭代器。

如果所有数组大小相同,则可以始终使用传统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]);
}
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
        }
    }
}

即使您有不同大小的数组,以下解决方案也能工作。如果所有数组的大小都相同,则可以始终使用单个迭代器。

static void Main(string[] args)
    {
        string[] a = System.IO.File.ReadAllLines
        (@"E:testa.txt");
        string[] b = System.IO.File.ReadAllLines
        (@"E:testb.txt");
        string[] c= System.IO.File.ReadAllLines
        (@"E:testc.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();
    }

最新更新