Split IEnumerable In Groups - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Split IEnumerable In Groups

Demo Code


using System.Linq;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;

public class Main{
        public static IEnumerable<List<TSource>> SplitInGroups<TSource>(this IEnumerable<TSource> values, int groupSize)
        {//from  w  ww. j  a va2s.  co m
            var asList = values as List<TSource>;
            if (asList != null && asList.Count <= groupSize)
            {
                yield return asList;
                yield break;
            }

            var currentList = new List<TSource>(groupSize);

            foreach (var value in values)
            {
                if (currentList.Count >= groupSize)
                {
                    yield return currentList;
                    currentList = new List<TSource>(groupSize);
                }
                currentList.Add(value);
            }

            if (currentList.Count > 0)
                yield return currentList;
        }
}

Related Tutorials