How to split an array into a group of n elements each? How to split an array into a group of n elements each? arrays arrays

How to split an array into a group of n elements each?


This will generate an array of string arrays having 3 elements:

int i = 0;var query = from s in testArray            let num = i++            group s by num / 3 into g            select g.ToArray();var results = query.ToArray();


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);