Search code examples
c#ienumerable

How to loop through IEnumerable in batches


I am developing a C# program which has an "IEnumerable users" that stores the ids of 4 million users. I need to loop through the IEnumerable and extract a batch 1000 ids each time to perform some operations in another method.

How do I extract 1000 ids at a time from start of the IEnumerable, do some thing else, then fetch the next batch of 1000 and so on?

Is this possible?


Solution

  • Sounds like you need to use Skip and Take methods of your object. Example:

    users.Skip(1000).Take(1000)
    

    this would skip the first 1000 and take the next 1000. You'd just need to increase the amount skipped with each call

    You could use an integer variable with the parameter for Skip and you can adjust how much is skipped. You can then call it in a method.

    public IEnumerable<user> GetBatch(int pageNumber)
    {
        return users.Skip(pageNumber * 1000).Take(1000);
    }