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
  • 27,221
  • 105
  • 339
  • 599
SuperJMN
  • 13,110
  • 16
  • 86
  • 185

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ç
  • 100,147
  • 13
  • 119
  • 184