Partitioning Operators and Paging Using Partitioning Operators in LINQ

Introduction

This article explains partitioning operators in LINQ.

The following are the types of partitioning operators.

  1. Take
  2. Skip
  3. TakeWhile
  4. SkipWhile

Take Method: The take method returns the number of elements from a collection specified as a parameter.

Let's look at an example of this Take method.

Create a new console application.



In the main method of this program class, create a new List of strings.

  1. static void Main(string[] args)  
  2. {  
  3.    List<String> Days = new List<string>()   
  4.    {  
  5.       "Monday""Tuesday""Wednesday","Thrusday""Friday""Saturday","Sunday"  
  6.    };  
  7. }  
To retrieve and print the days on the console window, we can use a foreach loop
  1. foreach (string day in Days)  
  2. {  
  3.    Console.WriteLine(day);  
  4. }  
Run the application.



We got the output as expected.

Now let's say for some reason we want only the first three items to be returned from the list object and to display them on the console.

One way to do that is with a for loop.
  1. for (int i = 0; i < Days.Count; i++)  
  2. {  
  3.    if (i == 3)  
  4.    {  
  5.        break;  
  6.    }  
  7.    else  
  8.    {  
  9.        Console.WriteLine(Days[i]);  
  10.    }  
  11. }  
Using the count property we will get the total number of items present in the Days list object. As we know these list items are added on a 0 based index and we want only the first three items meaning from 0 to 2. So, if the value i is 3 then we want this loop to break else we passed the value of i as an index to the Days list object.

Run the application.



The other way to do the same thing is by invoking the Take method on the Days list object.



Look at the type of parameter this "Take" method expects as an integer value. If we pass the value as 3 then this "Take" method will return the specified number of elements from the start.

Look at the return type of this method, it returns IEnumerable of string. So, we can create an object of that type and store the returning elements.
  1. IEnumerable<string> ThreeItems = Days.Take<string>(3);  
To retrieve all the elements from this ThreeItems, we can use a foreach loop.
  1. IEnumerable<string> ThreeItems = Days.Take<string>(3);  
  2. foreach (string days in ThreeItems)  
  3. {  
  4.    Console.WriteLine(days);  
  5. }  
Run the application.


Skip Method: To skip the number of elements from a sequence of elements, use the Skip method.

Let's say for some reason we want to skip the first three elements of the list object. The first way to do this is with a for loop.
  1. for (int i = 0; i < Days.Count; i++)  
  2. {  
  3.     if (i <= 2)  
  4.     {  
  5.        continue;  
  6.     }  
  7.     else  
  8.     {  
  9.        Console.WriteLine(Days[i]);  
  10.     }  
  11.  }   
In the preceding code, we are first checking if the value of i is less than or equal to 2. If it is true then continue. That means it will not execute the rest of the code and will go back to the for loop and increment the value by 1 and then again it will check the same thing and once the value of i is greater than 2 then it will go to the else block and display the element.

Run the application.


Let's see how to do the same thing using the Skip method.

To use this Skip method, all we need to do is invoke this method on the list object, in other words Days.



Look at the type of value this parameter expects. It expects an integer and if we pass 2 in here then it will skip the first three elements from the start and return the remaining elements.

Look at the return type of the Skip method, It returns an IEnumerable of string back. So, store the returning elements in an IEnumerable<string> object.
  1. IEnumerable<string> SkipThree = Days.Skip<string>(2);  
To retrieve all the elements from this SkipThree object, we can use a foreach loop and display those elements on the console window.
  1. IEnumerable<string> SkipThree = Days.Skip<string>(2);  
  2. foreach (string days in SkipThree)  
  3. {  
  4.     Console.WriteLine(days);  
  5. }  
Run the application.



TakeWhile Method

Take method returns the number of elements from a collection based on the count value we pass in as a parameter in the Take method.

The TakeWhile method returns the numbers of elements from a collection as long as the given condition is true.

To use this TakeWhile method, all we need to do is invoke it on the Days list object.



Look at the type of the parameter this TakeWhile method expects, a predicate of type string and it will return the elements back until the condition is true.

Let's say we want only those days whose length is equal to 6.

  1. IEnumerable<string> getByT = Days.TakeWhile<string>(x => x.Length == 6);  
To retrieve all the elements from this getByT object we can use a foreach loop.
  1. IEnumerable<string> getByT = Days.TakeWhile<string>(x => x.Length == 6);  
  2. foreach (string days in getByT)  
  3. Console.WriteLine(days);  
Run the application.



SkipWhileMethod

Skip method skips the number of elements from a collection based on the count value we pass in as a parameter of the skip method.

SkipWhile does the same thing but it skips the elements based on a condition and the condition we pass in is nothing but a predicate.

Let's say we want to skip an element from a collection whose length is equal to 6.

  1. IEnumerable<string> getByS = Days.SkipWhile<string>(x => x.Length == 6);  
To retrieve the remaining elements use foreach loop.
  1. IEnumerable<string> getByS = Days.SkipWhile<string>(x => x.Length == 6);  
  2. foreach (string days in getByS)  
  3. Console.WriteLine(days);  
Run the application.



Paging using Skip and Take partitioning operators

Create a new console application and create a class “Customer”.



In the Customer class add five auto-implemented properties.
 


In the same class create a static method that will return a list of customers back.



In the RetrieveCustomer static method create a new List<Customer> object and inside this object create 12 different customers object.

The entire Customer class looks like this.
  1. class Customer  
  2. {  
  3.     public int c_Id { getset; }  
  4.     public string c_Name { getset; }  
  5.     public string Gender { getset; }  
  6.     public string Email { getset; }  
  7.     public string City { getset; }  
  8.   
  9.     public static List<Customer> RetrieveCustomer()  
  10.     {  
  11.         /*create a new List of Customer object and in object create 
  12.         12 different customers object. 
  13.         */  
  14.         List<Customer> CustomerList = new List<Customer>()   
  15.         {  
  16.             //object one  
  17.             new Customer()   
  18.             {  
  19.                 c_Id = 3241,c_Name = "Michael",Gender = "Male",City = "San Andreas",Email ="[email protected]"  
  20.             },  
  21.   
  22.             //object two  
  23.             new Customer()   
  24.             {  
  25.                 c_Id = 1232,c_Name = "Trevor",Gender = "Male",City = "Las Vegas",Email ="[email protected]"  
  26.             },  
  27.   
  28.             //obect three  
  29.             new Customer()   
  30.             {  
  31.                 c_Id = 4513,c_Name = "Aiden Pearce",Gender = "Male",City = "Chicago",Email ="[email protected]"  
  32.             },  
  33.   
  34.             //object four  
  35.             new Customer()   
  36.             {  
  37.                 c_Id = 5544,c_Name = "Lara Croft",Gender = "Female",City = "New York",Email ="[email protected]"  
  38.             },  
  39.   
  40.             //object five  
  41.             new Customer()   
  42.             {  
  43.                 c_Id = 5654,c_Name = "Sam Fisher",Gender = "Male",City = "Istanbul",Email ="[email protected]"  
  44.             },  
  45.   
  46.             //object six  
  47.             new Customer()   
  48.             {  
  49.                 c_Id = 7895,c_Name = "Bryan Mills",Gender = "Male",City = "Shanghai",Email ="[email protected]"  
  50.             },  
  51.   
  52.             //object seven  
  53.             new Customer()   
  54.             {  
  55.                 c_Id = 5461,c_Name = "Black Widow",Gender = "Female",City = "Nepal",Email ="[email protected]"  
  56.             },  
  57.   
  58.             //object eight  
  59.             new Customer()   
  60.             {  
  61.                 c_Id = 9872,c_Name = "T-Bone",Gender = "Male",City = "Chicago",Email ="[email protected]"  
  62.             },  
  63.   
  64.             //object nine  
  65.             new Customer()   
  66.             {  
  67.                 c_Id = 1289,c_Name = "Sara",Gender = "Female",City = "Singapore",Email ="[email protected]"  
  68.             },  
  69.   
  70.             //object ten  
  71.             new Customer()   
  72.             {  
  73.                 c_Id = 4657,c_Name = "Natasha",Gender = "Female",City = "Paris",Email ="[email protected]"  
  74.             },  
  75.   
  76.             //object eleven  
  77.             new Customer()   
  78.             {  
  79.                 c_Id = 3657,c_Name = "James",Gender = "Male",City = "Germany",Email ="[email protected]"  
  80.             },  
  81.   
  82.             //object twelve  
  83.             new Customer()   
  84.             {  
  85.                 c_Id = 5463,c_Name = "Max",Gender = "Male",City = "San Andreas",Email ="[email protected]"  
  86.             },  
  87.         };  
  88.         return CustomerList;  
  89.     }  
  90. }  
So, we have added all twelve objects to the CustomerList.

Now in the Main method of the Program class invoke the RetrieveCustomer method and since this method is a static method we don't need to create an instance of the Customer class.



Now let's say we want to prompt the users to input a number between 1 and 4 based on which the 12 customers records will be displayed and in each page there will be three records.

For example, if the user types 1 then the first three records will be displayed and once the records are displayed we will again prompt the user to enter a page number. If the user types 2 then we want to skip the first three records and display the next three records and so on.

So, let's see how to do Paging using the Skip and Take methods.

Step 1

The first thing we need to do is prompt the user to enter a page number.



Step 2

The next step is to check if the p_num, in other words PageNumber, is between 1 and 4.
  1. do   
  2. {  
  3.   Console.WriteLine("Please enter a page number between 1 and 4");  
  4.   int p_num = Convert.ToInt32(Console.ReadLine());  
  5.   if (p_num >=1 && p_num <= 4) { }  
  6. }  
Step 3

The number of records that we want to display in each page, in other words from 1 to 4, is 3. So, create a new constant variable of type integer and assign a value of 3.
  1. if (p_num >=1 && p_num <= 4)   
  2. {  
  3.    const int Size = 3;  
  4. }  
Step 4
 
The next step is very important.
  1. IEnumerable<Customer> customers = c.Skip((p_num - 1) * Size).Take(3);  
How it works
  1. If the user passes 1 as a page number then that number will be assigned as a value for the p_num variable.

  2. Once it is assigned, the p_num value will be passed as a parameter in the Skip method.

  3. Inside the Skip method we passed an expression ((p_num - 1)*Size), so the page number that user the passes will be subtracted by 1 and then it will be multiplied by the page size (Size) which is 3. So, the expression will look like this (1-1)*3 that will provide the result as 0. So, it will skip 0 records and the Take method will take 3 records from the beginning because we have specified the number of records we want in a single page as 3 for the Size variable.

  4. If the user passes 2 as a value for p_num, the expression will look like this ((2-1) * 3). This time the skip method will skip 3 records and the Take method will display the next three records and so on.

Step 5

The next step is to retrieve all the Customers from IEnumerable of customers and for that we can use a foreach loop.

  1. foreach (Customer customer in customers)  
  2.  {  
  3.     Console.WriteLine("Id:{0} Name:{1} Gender:{2} City:{3} Email:                         4} ", customer.c_Id, customer.c_Name, customer.Gender, customer.City, customer.Email);  
  4.  }  
Code snippet for the Main Method
  1. static void Main(string[] args)  
  2. {  
  3.     List<Customer> c = Customer.RetrieveCustomer();  
  4.     do  
  5.     {  
  6.         Console.WriteLine("Please enter a page number between 1 and 4");  
  7.         int p_num = Convert.ToInt32(Console.ReadLine());  
  8.         if (p_num >= 1 && p_num <= 4)  
  9.         {  
  10.             const int Size = 3;  
  11.   
  12.             IEnumerable<Customer> customers = c.Skip((p_num - 1) * Size).Take(3);  
  13.             Console.WriteLine("Records in page number " + p_num);  
  14.   
  15.             foreach (Customer customer in customers)  
  16.             {  
  17.                 Console.WriteLine("Id:{0} Name:{1} Gender:{2} City:{3} Email:{4} ",  
  18.                 customer.c_Id, customer.c_Name, customer.Gender,  
  19.                 customer.City, customer.Email  
  20.                 );  
  21.             }  
  22.             Console.WriteLine();  
  23.         }  
  24.         else  
  25.         {  
  26.             Console.WriteLine("Please enter a valid page number");  
  27.         }  
  28.     } while (true);  
  29. }  
Run the application.
 
code snippet

Type 1 and press Enter.



In page number one we got the first three records of the customers.

Type 2 and press Enter.
.


In page number two the first three records are skipped and the next three records are displayed.

Type 3 and press Enter.



Type 4 and press Enter.



Summary

In this article we learned about the Skip, Take, SkipWhile, TakeWhile partitioning operators and we have also seen how to implement paging using partitioning operators.

I hope you like it. Thank you.


Similar Articles