Skip to content

Instantly share code, notes, and snippets.

@SeloSlav
Last active June 13, 2018 07:39
Show Gist options
  • Save SeloSlav/4236f034fbf76ed11f0558939daedabe to your computer and use it in GitHub Desktop.
Save SeloSlav/4236f034fbf76ed11f0558939daedabe to your computer and use it in GitHub Desktop.
A utility class that chunks up a list to help you display your data in columns.
using System.Collections.Generic;
using System.Linq;
namespace YeetClub.WebPlatform.Application.Utilities
{
public static class BatchList
{
public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(
this IEnumerable<TSource> source, int size)
{
TSource[] bucket = null;
var count = 0;
foreach (var item in source)
{
if (bucket == null)
bucket = new TSource[size];
bucket[count++] = item;
if (count != size)
continue;
yield return bucket;
bucket = null;
count = 0;
}
if (bucket != null && count > 0)
yield return bucket.Take(count);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment