1

What is the easiest way to convert [a, b, c, d] to an array of consecutive pairs of its elements using LINQ [[a, b], [c, d]] ? Is it possible at all?

x = [a, b, c, d] → y = [[a, b], [c, d]]

P.S. If not LINQ then how it can be done in a simplest and efficient way?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
NoWar
  • 36,338
  • 80
  • 323
  • 498

1 Answers1

4

Yes it is possible, :

var result = yourCollection
             .Select((x,idx) => new { x, idx })
             .GroupBy(g => g.idx / 2)
             .Select(g => g.Select(p => p.x).ToArray())
             .ToArray();

Since there is no built-in method to do this directly, the code looks like messy.It would be better if you can use Batch method from MoreLINQ library.Then you can just use:

var result = yourCollection.Batch(2).Select(x => x.ToArray()).ToArray();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • That's awesome and working solution! I appreciate time you spent and your knowledge, man! Thank you very much! – NoWar Jul 02 '14 at 13:43