Last active
June 11, 2016 06:25
-
-
Save kuchikios/27a884eda09eeafd31817b427071c050 to your computer and use it in GitHub Desktop.
任意の要素数ごとに分割した列挙を取得する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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