From 45eb0ef415049d0399435b7adeb7596ee8f9c680 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 20 Jul 2021 17:18:15 +0100 Subject: [PATCH] Add IReadOnlyCollection.Split(int) Yields the same results as IEnumerable.Split(int), except is able to avoid a hidden allocation with the benefit of knowing the collection size ahead of time --- .../CollectionExtensions.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 X10D/src/CollectionExtensions/CollectionExtensions.cs diff --git a/X10D/src/CollectionExtensions/CollectionExtensions.cs b/X10D/src/CollectionExtensions/CollectionExtensions.cs new file mode 100644 index 0000000..c10f765 --- /dev/null +++ b/X10D/src/CollectionExtensions/CollectionExtensions.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace X10D +{ + /// + /// Extension methods for and . + /// + public static class CollectionExtensions + { + /// + /// Splits into chunks of size . + /// + /// Any type. + /// The collection to split. + /// The maximum length of the nested collection. + /// + /// An containing an of + /// whose lengths are no greater than . + /// + public static IEnumerable> Split(this IReadOnlyCollection value, int chunkSize) + { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + + var count = value.Count; + chunkSize = chunkSize.Clamp(1, count); + + for (var i = 0; i < count / chunkSize; i++) + { + yield return value.Skip(i * chunkSize).Take(chunkSize).ToArray(); + } + } + } +}