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:
parent
d6e8471239
commit
45eb0ef415
38
X10D/src/CollectionExtensions/CollectionExtensions.cs
Normal file
38
X10D/src/CollectionExtensions/CollectionExtensions.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user