Skip to content

Instantly share code, notes, and snippets.

@kuchikios
Last active June 11, 2016 06:25
Show Gist options
  • Save kuchikios/27a884eda09eeafd31817b427071c050 to your computer and use it in GitHub Desktop.
Save kuchikios/27a884eda09eeafd31817b427071c050 to your computer and use it in GitHub Desktop.
任意の要素数ごとに分割した列挙を取得する
using System;
using System.Collections.Generic;
namespace kuchikios.Qiita
{
public static class EnumerableEx
{
public static IEnumerable<TValue[ ]> Split<TValue>( this IEnumerable<TValue> source, int blockCount, bool includeLastFractionBlock = false )
{
if ( default( IEnumerable<TValue> ) == source ) throw new ArgumentNullException( "source", "参照がありません" );
if ( 1 > blockCount ) throw new ArgumentOutOfRangeException( "blockCount", "範囲外の値です" );
var values = new List<TValue>( );
foreach ( var value in source )
{
values.Add( value );
if ( blockCount == values.Count )
{
yield return values.ToArray( );
values.Clear( );
}
}
if ( 0 < values.Count )
{
if ( blockCount == values.Count || includeLastFractionBlock )
{
yield return values.ToArray( );
}
values.Clear( );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment