Take and Skip Methods in LINQ

Suppose you have a requirement to print a collection but in m chunk and n times. To understand it better, You can also relate it to operating system; you read m pages one at a time and your data in size K is dispersed over M pages. That means each page contains M \ K data.

The question that arises is: How to read the data easily from each chunk.

Answer: Use linq to achieve the desired behavior,

  1. private static IEnumerable < int > PrintPages5AtATimes(List < int > intList, int iteration, int page, int pageSize)  
  2. {  
  3.     //pageSize 5  
  4.     //page 20  
  5.     // iteration 20 19 18 17 ......1  
  6.     return intList.Skip(pageSize * iteration - pageSize).Take(pageSize);  
  7. }  
Usage:
  1. Action < int > action = i =>  
  2. {  
  3.     Debug.WriteLine(i);  
  4. };  
  5. //print 5 each time  
  6. int page = 20, pageSize = 5;  
  7. for (int i = page; i <= page && i > 0; i--)  
  8. {  
  9.     IEnumerable < int > result = PrintPages5AtATime(intList, i, page, pageSize);  
  10.     Debug.WriteLine("\n");  
  11.     Debug.WriteLine(i + " Page");  
  12.     Debug.WriteLine("\n");  
  13.     Array.ForEach(result.ToArray(), action);  
  14. }  
Let’s assume your 100 MB data is distributed over 20 pages each of size 5MB. The code above helps retrieving each check one by one in reverse order. That means it prints 20 chunks each containing 5 elements.

Output:

Skip method skips the number of elements passed in to it from the start of the IEnumerable collection and Take method selects the next n number of elements passed in to it as an argument.

In first iteration we have 100 elements in total, 95 are ignored and the next 5 are selected and in second iteration initial 90 are ignore and next 5 are selected and so on and so forth.

output
Next Recommended Reading InsertAllOnSubmit Method in LINQ to SQL