Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

What is the best way to group an array into a list of array of n elements each in c# 4.

E.g

string[] testArray = { "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8" }; 

should be split into if we take n=3.

string[] A1 = {"s1", "s2", "s3"}; string[] A2 = {"s4", "s5", "s6"}; string[] A3 = {"s7", "s8"}; 

May be a simple way using LINQ?

like image 919
Amitabh Avatar asked Aug 18 '10 17:08

Amitabh


People also ask

How do you split an array into a group?

We are required to write a JavaScript function that takes in an array of literals and a number and splits the array (first argument) into groups each of length n (second argument) and returns the two-dimensional array thus formed.

How do you split an array by a number?

To split a number into an array:Call the split() method on the string to get an array of strings. Call the map() method on the array to convert each string to a number.

How do you divide an array?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

How do you divide an array into 4 parts?

Given an array of n non-negative integers. Choose three indices i.e. (0 <= index_1 <= index_ 2<= index_3 <= n) from the array to make four subsets such that the term sum(0, index_1) – sum(index_1, index_2) + sum(index_2, index_3) – sum(index_3, n) is maximum possible.


2 Answers

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(); 
like image 138
kbrimington Avatar answered Sep 22 '22 13:09

kbrimington


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()); } 
like image 28
JaredPar Avatar answered Sep 21 '22 13:09

JaredPar