Search code examples
c#yield-return

C# Yield return list, not single object


I need batch wise sublist to process objects in batch. Parallel.ForEach is not feasible as the batch is posted to the HTTP request.

public IEnumerable<T> BatchProcess<T>(IEnumerable<T> list, int batchSize)
    {
        int page = 0;
        IEnumerable<T> batch;
        while ((batch = list.Skip(page).Take(batchSize)).Count() != 0)
        {
            page++;
            yield return batch; //Error CS0029  Cannot implicitly convert type 'System.Collections.Generic.List<T>' to 'T'
        }

    }

Error CS0029 Cannot implicitly convert type 'System.Collections.Generic.List' to 'T'.

Expecting "yeild return" to return a list of objects instead of returning a single object.


Solution

  • Your method signature should be

    public IEnumerable<IEnumerable<T>> BatchProcess<T>(IEnumerable<T> list, int batchSize)