Introduction
This article explains partitioning operators in LINQ.
The following are the types of partitioning operators.
- Take
- Skip
- TakeWhile
- 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.
- static void Main(string[] args)
- {
- List<String> Days = new List<string>()
- {
- "Monday", "Tuesday", "Wednesday","Thrusday", "Friday", "Saturday","Sunday"
- };
- }
To retrieve and print the days on the console window, we can use a foreach loop
- foreach (string day in Days)
- {
- Console.WriteLine(day);
- }
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.
- for (int i = 0; i < Days.Count; i++)
- {
- if (i == 3)
- {
- break;
- }
- else
- {
- Console.WriteLine(Days[i]);
- }
- }
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.
- IEnumerable<string> ThreeItems = Days.Take<string>(3);
To retrieve all the elements from this ThreeItems, we can use a foreach loop.
- IEnumerable<string> ThreeItems = Days.Take<string>(3);
- foreach (string days in ThreeItems)
- {
- Console.WriteLine(days);
- }
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.
- for (int i = 0; i < Days.Count; i++)
- {
- if (i <= 2)
- {
- continue;
- }
- else
- {
- Console.WriteLine(Days[i]);
- }
- }
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.
- 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.
- IEnumerable<string> SkipThree = Days.Skip<string>(2);
- foreach (string days in SkipThree)
- {
- Console.WriteLine(days);
- }
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.
- 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.
- IEnumerable<string> getByT = Days.TakeWhile<string>(x => x.Length == 6);
- foreach (string days in getByT)
- 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.
- IEnumerable<string> getByS = Days.SkipWhile<string>(x => x.Length == 6);
To retrieve the remaining elements use foreach loop.
- IEnumerable<string> getByS = Days.SkipWhile<string>(x => x.Length == 6);
- foreach (string days in getByS)
- 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.
- class Customer
- {
- public int c_Id { get; set; }
- public string c_Name { get; set; }
- public string Gender { get; set; }
- public string Email { get; set; }
- public string City { get; set; }
-
- public static List<Customer> RetrieveCustomer()
- {
-
-
-
- List<Customer> CustomerList = new List<Customer>()
- {
-
- new Customer()
- {
- c_Id = 3241,c_Name = "Michael",Gender = "Male",City = "San Andreas",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 1232,c_Name = "Trevor",Gender = "Male",City = "Las Vegas",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 4513,c_Name = "Aiden Pearce",Gender = "Male",City = "Chicago",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 5544,c_Name = "Lara Croft",Gender = "Female",City = "New York",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 5654,c_Name = "Sam Fisher",Gender = "Male",City = "Istanbul",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 7895,c_Name = "Bryan Mills",Gender = "Male",City = "Shanghai",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 5461,c_Name = "Black Widow",Gender = "Female",City = "Nepal",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 9872,c_Name = "T-Bone",Gender = "Male",City = "Chicago",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 1289,c_Name = "Sara",Gender = "Female",City = "Singapore",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 4657,c_Name = "Natasha",Gender = "Female",City = "Paris",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 3657,c_Name = "James",Gender = "Male",City = "Germany",Email ="[email protected]"
- },
-
-
- new Customer()
- {
- c_Id = 5463,c_Name = "Max",Gender = "Male",City = "San Andreas",Email ="[email protected]"
- },
- };
- return CustomerList;
- }
- }
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.
- do
- {
- Console.WriteLine("Please enter a page number between 1 and 4");
- int p_num = Convert.ToInt32(Console.ReadLine());
- if (p_num >=1 && p_num <= 4) { }
- }
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.
- if (p_num >=1 && p_num <= 4)
- {
- const int Size = 3;
- }
Step 4
The next step is very important.
- IEnumerable<Customer> customers = c.Skip((p_num - 1) * Size).Take(3);
How it works
- If the user passes 1 as a page number then that number will be assigned as a value for the p_num variable.
- Once it is assigned, the p_num value will be passed as a parameter in the Skip method.
- 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.
- 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.
- foreach (Customer customer in customers)
- {
- Console.WriteLine("Id:{0} Name:{1} Gender:{2} City:{3} Email: 4} ", customer.c_Id, customer.c_Name, customer.Gender, customer.City, customer.Email);
- }
Code snippet for the Main Method
- static void Main(string[] args)
- {
- List<Customer> c = Customer.RetrieveCustomer();
- do
- {
- Console.WriteLine("Please enter a page number between 1 and 4");
- int p_num = Convert.ToInt32(Console.ReadLine());
- if (p_num >= 1 && p_num <= 4)
- {
- const int Size = 3;
-
- IEnumerable<Customer> customers = c.Skip((p_num - 1) * Size).Take(3);
- Console.WriteLine("Records in page number " + p_num);
-
- foreach (Customer customer in customers)
- {
- Console.WriteLine("Id:{0} Name:{1} Gender:{2} City:{3} Email:{4} ",
- customer.c_Id, customer.c_Name, customer.Gender,
- customer.City, customer.Email
- );
- }
- Console.WriteLine();
- }
- else
- {
- Console.WriteLine("Please enter a valid page number");
- }
- } while (true);
- }
Run the application.
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.