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?
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.
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.
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.
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.
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()); }
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