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,
- private static IEnumerable < int > PrintPages5AtATimes(List < int > intList, int iteration, int page, int pageSize)
- {
- //pageSize 5
- //page 20
- // iteration 20 19 18 17 ......1
- return intList.Skip(pageSize * iteration - pageSize).Take(pageSize);
- }
- Action < int > action = i =>
- {
- Debug.WriteLine(i);
- };
- //print 5 each time
- int page = 20, pageSize = 5;
- for (int i = page; i <= page && i > 0; i--)
- {
- IEnumerable < int > result = PrintPages5AtATime(intList, i, page, pageSize);
- Debug.WriteLine("\n");
- Debug.WriteLine(i + " Page");
- Debug.WriteLine("\n");
- Array.ForEach(result.ToArray(), action);
- }
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.


Avikshith AradhyaPosted Jun 8, 2016, 5:45 AM
Good Article.
Bhuvanesh MohankumarPosted May 6, 2016, 3:55 PM
Good one...
Santhakumar MunuswamyPosted Nov 16, 2015, 11:56 PM
Nice share