May 19, 2015

Linq TakeBy

I was about to write such an extension
But then desided to google for it first, and voila:

Code:
/// <summary>
/// <paramref name="source"/>中の要素を<paramref name="count"/>
/// 個ごとにまとめ直します。
/// 最後の要素数が足りない場合は足りないまま返します。
/// </summary>
public static IEnumerable<IEnumerable<TSource>> TakeBy<TSource>(this IEnumerable<TSource> source, int count)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (count < 1)
    {
        throw new ArgumentOutOfRangeException("count");
    }
    while (source.Any())
    {
        yield return source.Take(count);
        source = source.Skip(count);
    }
}

got it here
Isn't it nice?

ps: this variant is much faster