23

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?

7 Answers 7

26

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();
2
  • 1
    +1, The only downside of this approach is that it's eagerly evaluated. The entire query must be processed before a single element can be returned.
    – JaredPar
    Aug 18, 2010 at 17:26
  • @JaredPar: Point well taken; however, depending on the size of the collection, or the nature of the processing, lazy evaluation may be overrated. Even so, +1 to your solution for providing a valid lazy approach. Aug 18, 2010 at 17:30
9

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());
}
1
  • Perfect answer. But should provide an example of how it solves the problem in the question. Dec 30, 2014 at 13:23
8
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);
4

In .NET 6+, the Chunk extension method was added, its really well summarized by this article here: https://exceptionnotfound.net/bite-size-dotnet-6-chunk-in-linq/

string[] testArray = { "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8" };
testArray.Chunk(3);
2
  • 1
    Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community? Oct 2, 2023 at 0:15
  • 1
    Thank you, this is a great answer. A real straight-shooter, upper management potential here. Apr 8 at 14:02
2

If it is actually arrays that you are working with rather than general IEnumerables, and especially if the arrays are very large, then this method is a very fast and memory effecient way to do it. If you really just want a LINQ statement, then nevermind.

    private static T[][] SliceArray<T>(T[] source, int maxResultElements)
    {
        int numberOfArrays = source.Length / maxResultElements;
        if (maxResultElements * numberOfArrays < source.Length)
            numberOfArrays++;
        T[][] target = new T[numberOfArrays][];
        for (int index = 0; index < numberOfArrays; index++)
        {
            int elementsInThisArray = Math.Min(maxResultElements, source.Length - index * maxResultElements);
            target[index] = new T[elementsInThisArray];
            Array.Copy(source, index * maxResultElements, target[index], 0, elementsInThisArray);
        }
        return target;
    }
1

You can use this Extension

public static class Extension
{
    private static IEnumerable<TList> Split<TList, T>(this TList value, int countOfEachPart) where TList : IEnumerable<T>
    {
        int cnt = value.Count() / countOfEachPart;
        List<IEnumerable<T>> result = new List<IEnumerable<T>>();
        for (int i = 0; i <= cnt; i++)
        {
            IEnumerable<T> newPart = value.Skip(i * countOfEachPart).Take(countOfEachPart).ToArray();
            if (newPart.Any())
                result.Add(newPart);
            else
                break;
        }

        return result.Cast<TList>();
    }

    public static IEnumerable<IDictionary<TKey, TValue>> Split<TKey, TValue>(this IDictionary<TKey, TValue> value, int countOfEachPart)
    {
        IEnumerable<Dictionary<TKey, TValue>> result = value.ToArray()
                                                            .Split(countOfEachPart)
                                                            .Select(p => p.ToDictionary(k => k.Key, v => v.Value));
        return result;
    }

    public static IEnumerable<IList<T>> Split<T>(this IList<T> value, int countOfEachPart)
    {
        return value.Split<IList<T>, T>(countOfEachPart);
    }

    public static IEnumerable<T[]> Split<T>(this T[] value, int countOfEachPart)
    {
        return value.Split<T[], T>(countOfEachPart);
    }

    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> value, int countOfEachPart)
    {
        return value.Split<IEnumerable<T>, T>(countOfEachPart);
    }
}
1

MoreLinq provides Batch extension method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.