Skip to content

Commit d02ad24

Browse files
committed
Added queryable chunking
1 parent 9d92a3f commit d02ad24

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// MADE Apps licenses this file to you under the MIT license.
2+
// See the LICENSE file in the project root for more information.
3+
4+
namespace MADE.Collections
5+
{
6+
using System.Collections.Generic;
7+
using System.Linq;
8+
9+
/// <summary>
10+
/// Defines a collection of extensions for queryable objects.
11+
/// </summary>
12+
public static class QueryableExtensions
13+
{
14+
/// <summary>
15+
/// Chunks a query of items into the specified chunk size.
16+
/// </summary>
17+
/// <typeparam name="T">The type of item.</typeparam>
18+
/// <param name="source">The source query to chunk.</param>
19+
/// <param name="chunkSize">The chunk size.</param>
20+
/// <returns>A collection of queries containing the chunked items.</returns>
21+
public static IEnumerable<IQueryable<T>> Chunk<T>(this IQueryable<T> source, int chunkSize = 25)
22+
{
23+
int idx = 0;
24+
while (true)
25+
{
26+
IQueryable<T> q = idx == 0
27+
? source
28+
: source.Skip(idx * chunkSize);
29+
IQueryable<T> chunk = q.Take(chunkSize);
30+
if (!chunk.Any())
31+
{
32+
yield break;
33+
}
34+
35+
yield return chunk.AsQueryable();
36+
idx++;
37+
}
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)