How can I formulate a straightforward LINQ query (using query syntax) that performs this grouping?
Extension method (using Jesse's answer):
public static IEnumerable<T[]> GroupToChunks<T>(this IEnumerable<T> items, int chunkSize)
{
if (chunkSize <= 0)
{
throw new ArgumentException("Chunk size must be positive.", "chunkSize");
}
return
items.Select((item, index) => new { item, index })
.GroupBy(pair => pair.index / chunkSize, pair => pair.item)
.Select(grp => grp.ToArray());
}
For those who prefer the LINQ methods (with lambda expressions), here is Dimitriy Matveev's answer converted:
var result = array
.Select((value, index) => new { Value = value, Index = index })
.GroupBy(i => i.Index / chunkSize, v => v.Value);
If you need just an array of value
, instead of an IGrouping<T1, T2>
, then append the following:
.Select(x => x.ToArray())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With