C#: IEnuerablePartitionExtension
internal static class IEnumerablePartitionExtensions
{
public static IEnumerable<ICollection<T>> PartitionByPredicate<T>(this IEnumerable<T> seq, Func<T, T, bool> split)
{
var buffer = new List<T>();
foreach (var x in seq)
{
if (buffer.Any() && split(buffer.Last(), x))
{
yield return buffer;
buffer = new List<T>();
}
buffer.Add(x);
}
if (buffer.Any())
yield return buffer;
}
public static IEnumerable<ICollection<T>> PartitionByCount<T>(this IEnumerable<T> seq, int count)
{
var buffer = new List<T>(count);
foreach (var x in seq)
{
if (buffer.Count == count)
{
yield return buffer;
buffer = new List<T>(count);
}
buffer.Add(x);
}
if (buffer.Any()) yield return buffer;
}
}