user1526912 user1526912 - 18 days ago 4x
C# Question

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 Ienummerable 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 some thing else then fetch the next batch of 1000 and so on ?

Is this possible?


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


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);