Search code examples
c#linqtake

Take each lines as group in c# using linq


I have an array of string that contains 1000 lines, how to take each 25 lines and group them into one text using linq c#. I can use loops , but I need the code using linq.


Solution

  • var blocks = File.ReadLines(filename)
                        .Select((s, i) => new { s, i })
                        .GroupBy(x => x.i / 25)
                        .Select(g => String.Join(" ", g.Select(x => x.s)))
                        .ToList();
    

    You can also use Morelinq's Batch method: https://code.google.com/p/morelinq/source/browse/MoreLinq/Batch.cs