简体   繁体   English

如何将列表写入文本文件。 每行写 50 个项目

[英]How to write a list to a text file. Write 50 items per line

I am working on a program where I read data from a file, store that data in a list and write that data to a new file in a special format.我正在开发一个程序,我从文件中读取数据,将该数据存储在列表中,然后将该数据以特殊格式写入新文件。 I have created the method to read the original file and store it in a list.我已经创建了读取原始文件并将其存储在列表中的方法。

The file I read from is a list of numbers.我读取的文件是一个数字列表。 One number per line.每行一个号码。

I'm having issue with my method that writes to the new file.我的写入新文件的方法有问题。 I'm having an issue with taking 50 items and writing them to a line and then taking the next 50 items and writing on the next line.我在取 50 个项目并将它们写入一行,然后取下 50 个项目并在下一行写入时遇到问题。 The method is taking the first 50 items and writing them and repeating those 50 items on each line.该方法是取前 50 个项目并编写它们并在每行上重复这 50 个项目。 I know this is because of my second for loop.我知道这是因为我的第二个 for 循环。 Just not sure how to fix.只是不知道如何修复。 any help would be appreciated.任何帮助,将不胜感激。 Below is my code:下面是我的代码:

public static void WriteFormattedTextToNewFile(List<string> groupedStrings)
{
    string file = @"C:\Users\e011691\Desktop\New folder\formatted.txt";
    StreamWriter sw = new StreamWriter(file, true);

    for (int i = 0; i < ReadFile.GroupedStrings.Count; i++)
    {
        sw.Write($"{DateTime.Now:yyyy MM dd  hh:mm:ss}\t\t");

        for (int j = 0; j < 50; j++)
        {
            sw.Write($"{ReadFile.GroupedStrings[j]}\t");
        }
        sw.WriteLine();
    }
    sw.Close();
}

I'll give you three options (and a bonus).我会给你三个选择(和一个奖金)。

First option.第一个选项。 Use a custom Chunk(int) linq operator using iterator blocks.使用迭代器块使用自定义Chunk(int) linq 运算符。 The trick is the inner method uses the same enumerator as the outer.诀窍是内部方法使用与外部方法相同的枚举器。 Seems like a lot of code, but once you have the Chunk() method, you can use it anywhere.看起来代码很多,但是一旦有了Chunk()方法,就可以在任何地方使用它。 Also note this option doesn't even need a List<string> .另请注意,此选项甚至不需要List<string> It will work with any IEnumerable<string> , since we never reference any elements by index.它适用于任何IEnumerable<string> ,因为我们从不通过索引引用任何元素。

public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> values, int chunkSize)
{
    var e = values.GetEnumerator();
    while (e.MoveNext())
    {
        yield return innerChunk(e, chunkSize);
    }
}

private static IEnumerable<T> innerChunk<T>(IEnumerator<T> e, int chunkSize)
{
    //If we're here, MoveNext() was already called once to advance between batches
    // Need to yield the value from that call.
    yield return e.Current;

    //start at 1, not 0, for the first yield above  
    int i = 1; 
    while(i++ < chunkSize && e.MoveNext()) //order of these conditions matters
    {
        yield return e.Current;
    }
}

public static void WriteFormattedTextToNewFile(IEnumerable<string> groupedStrings)
{
    string file = @"C:\Users\e011691\Desktop\New folder\formatted.txt";
    using (var sw = new StreamWriter(file, true))
    {   
        foreach(var strings in groupedStrings.Chunk(50))
        {
            sw.Write($"{DateTime.Now:yyyy MM dd  hh:mm:ss}\t\t");
            foreach(var item in strings)
            {
               sw.Write($"{item}\t");
            }
            sw.WriteLine();
        } 
    }
}

Here's a basic proof of concept Chunk() actually works .是概念 Chunk() 实际上有效的基本证明

As a bonus option, here is another way to use the Chunk() method from the first option.作为奖励选项,这是使用第一个选项中的Chunk()方法的另一种方法。 Note how small and straight-forward the actual method becomes, but the construction of the long full-line strings likely makes this less efficient.请注意实际方法变得多么小巧和直接,但长整行字符串的构造可能会降低效率。

public static void WriteFormattedTextToNewFile(IEnumerable<string> groupedStrings)
{
    string file = @"C:\Users\e011691\Desktop\New folder\formatted.txt";
    using (var sw = new StreamWriter(file, true))
    {   
        foreach(var strings in groupedStrings.Chunk(50))
        {
            sw.Write($"{DateTime.Now:yyyy MM dd  hh:mm:ss}\t\t");
            sw.WriteLine(string.Join("\t", strings));
        } 
    }
}

Second option.第二种选择。 Keep track using a separate integer/loop.使用单独的整数/循环跟踪。 Note the extra condition on the inner loop, still using the i value rather than j to reference the current position, and incrementing i in the inner loop.注意内循环的额外条件,仍然使用i值而不是j来引用当前位置,并在内循环中递增i This is called a Control/Break loop.这称为控制/中断循环。 Note how we are able to write the end line and initial date value on each line such that they also appear in the correct order in the code: first the header, then the items, then the footer, and we do it without complicated conditional checks.请注意我们如何能够在每一行上写入结束行和初始日期值,以便它们也以正确的顺序出现在代码中:首先是页眉,然后是项目,然后是页脚,并且我们无需复杂的条件检查即可完成.

public static void WriteFormattedTextToNewFile(List<string> groupedStrings)
{
    string file = @"C:\Users\e011691\Desktop\New folder\formatted.txt";
    using (var sw = new StreamWriter(file, true))
    {   
        int i = 0;
        while(i < groupedStrings.Count)
        {
           sw.Write($"{DateTime.Now:yyyy MM dd  hh:mm:ss}\t\t");
           for(int j = 0; j < 50 && i < groupedStrings.Count; j++)
           {
              sw.Write($"{groupedStrings[i]}\t");
              i++;
           }
           sw.WriteLine();
        }
    }
}

Third option.第三种选择。 Keep track using the modulus operator ( % ).使用模数运算符 ( % ) 进行跟踪。 This option (or a similar option using a second j value in the same loop) is where many would turn first, but beware;此选项(或在同一循环中使用第二个j值的类似选项)是许多人首先转向的地方,但要注意; this option is deceptively difficult to get right, especially as the problem gets more complicated.这个选项看似很难正确,尤其是当问题变得更加复杂时。

public static void WriteFormattedTextToNewFile(List<string> groupedStrings)
{
    string file = @"C:\Users\e011691\Desktop\New folder\formatted.txt";
    using (var sw = new StreamWriter(file, true))
    {
        for(int i = 0; i < groupedStrings.Count;i++)
        {
            if (i % 50 == 0)
            {
                if (i > 0) sw.WriteLine();
                sw.Write($"{DateTime.Now:yyyy MM dd  hh:mm:ss}\t\t");
            }

            sw.Write($"{groupedStrings[i]}\t");
        }
        sw.WriteLine();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM