Note :This post is first published on Mar-2013 in my previous blog Techkindle. Moving the content here.
There may be certain situations, When we have a number of objects in the list, but we need to split the objects into batches by batch size.
To achieve that we can use Skip and Take static methods in LINQ,
- Skip : Bypasses a specified number of elements in a sequence and then returns the remaining elements.
- Take : Returns a specified number of contiguous elements from the start of a sequence.
Using both these static methods, we can split the list into multiple lists based on the batch size.
While writing the source code, my main intention is to just show how to split the list into batch sizes. So didn’t take the validations, and other things into consideration.
- First of all creating a Student Class. Which is a template to create the Student objects. (We can use anonymous types also).
- Then writing a method to create a list of objects for student class. I have just given some random data, and creating some 23 objects.
- Then writing a method to split the passed list of objects into batches, based on the passed batch size.
- At last calling all the methods from the Main method. Here I am giving the full source code.
Happy Learning 🙂