Friday, March 15, 2013

Split the List of objects into Batches using LINQ

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 Do that we can use LINQ, Skip and Take static methods.
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 bother about the validations, and other things. Kindly ignore those things.
  1.  First of all creating a Student Class. Which is a template to create the Student objects. ( We can use anonymous types also).
  2.  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.
  3.  Then writing a method to split the passed list of objects into batches, based on the passed batch size.
  4.  At last calling all the methods from the Main method.
Here i am giving the full source code.
Output: