Skip to content

Instantly share code, notes, and snippets.

@wipiano
Last active August 1, 2017 15:40
Show Gist options
  • Save wipiano/fb98695958998b44f74619c70b6f14f6 to your computer and use it in GitHub Desktop.
Save wipiano/fb98695958998b44f74619c70b6f14f6 to your computer and use it in GitHub Desktop.
IEnumerable<T> を指定した要素数で分割する
namespace IEnumerableSplit
{
public static class IEnumerableExtensions
{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int size)
{
if (size <= 0)
{
throw new ArgumentOutOfRangeException($"{nameof(size)} は 0 より大きくなければなりません");
}
if (source == null)
{
throw new ArgumentNullException($"{nameof(source)} は null にできません");
}
var list = new List<T>(size);
foreach (var item in source)
{
list.Add(item);
if (list.Count == size)
{
yield return list.ToArray();
list.Clear();
}
}
if (list.Any())
{
yield return list;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment