For this kind of thing you should write a Chunkify
extension method. One good example you can get from Marc here. But due to the question it always returns an array with a fixed size and maybe null entries.
So maybe this implementation matches better your requirements:
/// <summary>
/// Divides an enumeration into smaller (same-sized) chunks.
/// </summary>
/// <typeparam name="T">The type of the elements within the sequence.</typeparam>
/// <param name="source">The sequence which should be breaked into chunks.</param>
/// <param name="size">The size of each chunk.</param>
/// <returns>An IEnumerable<T> that contains an IEnumerable<T> for each chunk.</returns>
public static IEnumerable<IEnumerable<T>> Chunkify<T>(this IEnumerable<T> source, int size)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (size < 1)
{
throw new ArgumentOutOfRangeException("size");
}
return ChunkifyImpl(source, size);
}
private static IEnumerable<IEnumerable<T>> ChunkifyImpl<T>(IEnumerable<T> source, int size)
{
using (var iter = source.GetEnumerator())
{
while (iter.MoveNext())
{
var chunk = new List<T>(size);
chunk.Add(iter.Current);
for (int i = 1; i < size && iter.MoveNext(); i++)
{
chunk.Add(iter.Current);
}
yield return chunk;
}
}
}
Now you can use this extension as follows:
foreach(var chunk in EntriesList.Chunkify(100))
{
service.InsertEntries(chunk);
Thread.Sleep(5000);
}