对于这种事情你应该写一个Chunkify
扩展方法。你可以从Marc 那里得到一个很好的例子。但是由于这个问题,它总是返回一个具有固定大小的数组,并且可能是空条目。
所以也许这个实现更符合您的要求:
/// <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;
}
}
}
现在您可以按如下方式使用此扩展:
foreach(var chunk in EntriesList.Chunkify(100))
{
service.InsertEntries(chunk);
Thread.Sleep(5000);
}