Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>You're better off using a library like <a href="http://morelinq.googlecode.com/" rel="noreferrer">MoreLinq</a>, but if you really had to do this using "plain LINQ", you can use <code>GroupBy</code>:</strong></p> <pre><code>var sequence = new[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; var result = sequence.Select((x, i) =&gt; new {Group = i/8, Value = x}) .GroupBy(item =&gt; item.Group, g =&gt; g.Value) .Select(g =&gt; g.Where(x =&gt; true)); // result is: { {1,2,3,4,5,6,7,8}, {9,10,11,12,13,14,15,16} } </code></pre> <p>Basically, we use the version of <code>Select()</code> that provides an index for the value being consumed, we divide the index by 8 to identify which group each value belongs to. Then we group the sequence by this grouping key. The last <code>Select</code> just reduces the <code>IGrouping&lt;&gt;</code> down to an <code>IEnumerable&lt;IEnumerable&lt;T&gt;&gt;</code> (and isn't strictly necessary since <code>IGrouping</code> is an <code>IEnumerable</code>).</p> <p>It's easy enough to turn this into a reusable method by factoring our the constant <code>8</code> in the example, and replacing it with a specified parameter. It's not necessarily the most elegant solution, and it is not longer a lazy, streaming solution ... but it does work.</p> <p>You could also write your own extension method using iterator blocks (<code>yield return</code>) which could give you better performance and use less memory than <code>GroupBy</code>. This is what the <code>Batch()</code> method of MoreLinq does IIRC.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload