Start New Partition by function on IEnumerable - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Start New Partition by function on IEnumerable

Demo Code


using System.Linq;
using System.Collections.Generic;
using System;//ww  w . j  a v a 2  s. co m

public class Main{
        public static IEnumerable<IReadOnlyList<T>> StartNewPartitionWhen<T>(this IEnumerable<T> sequence, Func<T, bool> predicate) {
            if (sequence == null) throw new ArgumentNullException("sequence");
            if (predicate == null) throw new ArgumentNullException("predicate");

            var curPartition = new List<T>();
            foreach (var e in sequence) {
                if (curPartition.Count > 0 && predicate(e)) {
                    yield return curPartition.ToArray();
                    curPartition.Clear();
                }
                curPartition.Add(e);
            }
            if (curPartition.Count > 0) {
                yield return curPartition;
            }
        }
}

Related Tutorials