Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could project the group number onto each item in the original list using <code>Select</code> and an anonymous type like this:</p> <pre><code>var assigned = Class.Students.Select( (item, index) =&gt; new { Student = item, GroupNumber = index / 20 + 1 }); </code></pre> <p>Then you can use it like this:</p> <pre><code>foreach (var item in assigned) { Console.WriteLine("Student = " + item.Student.Name); Console.WriteLine("You belong to Group " + item.GroupNumber.ToString()); } </code></pre> <p>Or if you wanted to pick off a particular group.</p> <pre><code>foreach (var student in assigned.Where(x =&gt; x.GroupNumber == 5)) { Console.WriteLine("Name = " + student.Name); } </code></pre> <p>Or if you wanted to actually group them to perform aggregates</p> <pre><code>foreach (var group in assigned.GroupBy(x =&gt; x.GroupNumber)) { Console.WriteLine("Average age = " + group.Select(x =&gt; x.Student.Age).Average().ToString()); } </code></pre> <p>Now if you just want to lump the items in batches and you do not care about having the batch number information you can create this simple extension method.</p> <pre><code>public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; Batch&lt;T&gt;(this IEnumerable&lt;T&gt; target, int size) { var assigned = target.Select( (item, index) =&gt; new { Value = item, BatchNumber = index / size }); foreach (var group in assigned.GroupBy(x =&gt; x.BatchNumber)) { yield return group.Select(x =&gt; x.Value); } } </code></pre> <p>And you could use your new extension method like this.</p> <pre><code>foreach (var batch in Class.Students.Batch(20)) { foreach (var student in batch) { Console.WriteLine("Student = " + student.Name); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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