1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-22 23:58:48 +00:00

Add IReadOnlyCollection<T>.Split(int)

Yields the same results as IEnumerable<T>.Split(int), except is able to
avoid a hidden allocation with the benefit of knowing the collection
size ahead of time
This commit is contained in:
Oliver Booth 2021-07-20 17:18:15 +01:00
parent d6e8471239
commit 45eb0ef415
No known key found for this signature in database
GPG Key ID: A4AC17007530E9B4

View File

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace X10D
{
/// <summary>
/// Extension methods for <see cref="ICollection{T}" /> and <see cref="IReadOnlyCollection{T}" />.
/// </summary>
public static class CollectionExtensions
{
/// <summary>
/// Splits <paramref name="value" /> into chunks of size <paramref name="chunkSize" />.
/// </summary>
/// <typeparam name="T">Any type.</typeparam>
/// <param name="value">The collection to split.</param>
/// <param name="chunkSize">The maximum length of the nested collection.</param>
/// <returns>
/// An <see cref="IEnumerable{T}" /> containing an <see cref="IEnumerable{T}" /> of <typeparamref name="T" />
/// whose lengths are no greater than <paramref name="chunkSize" />.
/// </returns>
public static IEnumerable<IReadOnlyCollection<T>> Split<T>(this IReadOnlyCollection<T> 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();
}
}
}
}