Search code examples
c#linqarrays.net-4.0

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


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?


Solution

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