Last active
August 1, 2017 15:40
-
-
Save wipiano/fb98695958998b44f74619c70b6f14f6 to your computer and use it in GitHub Desktop.
IEnumerable<T> を指定した要素数で分割する
This file contains 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
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