0

I would like to use LINQ to achieve this:

Having a string like "abcdefghijk" and a "chunk size" of 3,

  • The LINQ query should return

    {"abc", "def", "ghi", "jk" }
    
  • With chunk size of 4:

    {"abcd", "efgh", "ijk" }
    

I'm almost sure that I would have to use TakeWhile, or Zip, but I don't know how to use them!

Tiny
  • 26,031
  • 99
  • 315
  • 583
SuperJMN
  • 11,791
  • 11
  • 79
  • 162

1 Answers1

4

You can use Batch method from MoreLinq library:

var chunks = str.Batch(4).Select(x => new string(x.ToArray()).ToList();

This can also be done with GroupBy but the code won't look that pretty:

var chunks = str
          .Select((x,idx) => new { x, idx })
          .GroupBy(c => c.idx / 4)
          .Select(g => new string(g.Select(c => c.x).ToArray()))
          .ToList();
Selman Genç
  • 97,365
  • 13
  • 115
  • 182