How to split an array into a group of n elements each?
I don't think there's a great built-in method for this but you could write one like the following.
public static IEnumerable<IEnumerable<T>> GroupInto<T>( this IEnumerable<T> source, int count) { using ( var e = source.GetEnumerator() ) { while ( e.MoveNext() ) { yield return GroupIntoHelper(e, count); } } }private static IEnumerable<T> GroupIntoHelper<T>( IEnumerator<T> e, int count) { do { yield return e.Current; count--; } while ( count > 0 && e.MoveNext());}
int size = 3;var results = testArray.Select((x, i) => new { Key = i / size, Value = x }) .GroupBy(x => x.Key, x => x.Value, (k, g) => g.ToArray()) .ToArray();
If you don't mind the results being typed as IEnumerable<IEnumerable<T>>
rather than T[][]
then you can omit the ToArray
calls altogether:
int size = 3;var results = testArray.Select((x, i) => new { Key = i / size, Value = x }) .GroupBy(x => x.Key, x => x.Value);