合并列表而不将新列表的人口放在新行上

问题描述

我想将两个列表合并在一起,但我找到的方法将列表的填充物添加到新行中,就像这样。

parts on list one,parts on list one,parts on list two,

但是,我希望它看起来像这样。

parts on list one,parts on list two
parts on list one,parts on list two

这就是我必须将它们合并(+ 到目前为止的列表本身)

static void Main(string[] args)
    {
        iterateRoutes(@"C:\Users\peepee poopoo\gtfs\routes.txt",@"C:\Users\peepee poopoo\gtfs\calendar.txt");
        //log.ForEach(Console.WriteLine);
    }

    public static List<string> log = new List<string>();
    public static List<string> datesstd = new List<string>();
    public static List<string> datesEnd = new List<string>();

    public static void iterateRoutes(string rtname,string std)
    {
        foreach (var route in File.ReadAllLines(rtname)) // iterate file lines
        {
            var elements = route.Split(','); // split current line into elements
            log.Add(elements[0] + "," + elements[2] + "," + "2021426,20991231,"); // add first & third element to log
        }

        foreach (var route in File.ReadAllLines(std)) // iterate file lines
        {
            //var elements = route.Split(','); // split current line into elements
            //log.Add("," + elements[8]); // add first & third element to log
        }



        //datesstd.ForEach(Console.WriteLine);
        // datesEnd.ForEach(Console.WriteLine);

        log.AddRange(datesstd);
        log.ForEach(Console.WriteLine);
    }

我怎么能这样做?

解决方法

要加入文件,您可以使用 zip:

IEnumerable<string> fileOne = File.ReadLines("one.txt");
IEnumerable<string> fileTwo = File.ReadLines("two.txt");

// For each line in fileOne,take a line from fileTwo
// call these lines l1 and l2 respectively,and produce 
// a merged result.
IEnumerable<string> joined = fileOne.Zip(fileTwo,(l1,l2) => $"{l1}{l2}");

// write the result to a file
File.WriteAllLines("out.txt",joined);

// or materialize it to a list
List<string> lines = joined.ToList();

Zip documentation

所以如果我们有一个文件:

A
B
C

还有另一个文件:

D
E
F

那么结果就是

AD
BE
CF

Try it online。请注意,我在这里用我自己的假版本替换了 File.ReadLines,因为我使用的站点不支持读取文件。