Skip to content

Instantly share code, notes, and snippets.

@shibayan
Last active March 16, 2018 10:13
Show Gist options
  • Save shibayan/53349666834b6f889b2f to your computer and use it in GitHub Desktop.
Save shibayan/53349666834b6f889b2f to your computer and use it in GitHub Desktop.
忘れやすい拡張メソッドまとめ
public static class EnumerableExtensions
{
// https://stackoverflow.com/questions/3210824/divide-array-into-an-array-of-subsequence-array/29462069
public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(this IEnumerable<TSource> source, int size)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (size < 1)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
using (var enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
var batch = new List<TSource>(size)
{
enumerator.Current
};
for (int i = 1; i < size && enumerator.MoveNext(); i++)
{
batch.Add(enumerator.Current);
}
yield return batch;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment