Sunday, 16 July 2017

LINQ Skip and SkipWhile Partitioning operators in C#

In this article, I am going to explain you LINQ Skip and SkipWhile partitioning operators in C#. Below is the four partitioning operators in C#. Partitioning operators split the collection into two parts and returns one part only.
1) Skip - It skips element up-to specified position starting from first element in collection.
2) SkipWhile – It skip elements in the collection till the specified condition is true. It returns a new collection that includes all the remaining elements once the specified condition becomes false for any element.
3) Take 4) TakeWhile  (click here to read about Take and TakeWhile)

Let's understand the these operators with examples.

Using Skip Partitioning Operator In LINQ

Example 1

Let's apply Skip operator on a string array which contains some words. Here Skip operator will skip first 4 element from collection and returns remaining element from array.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
var skipFirstFourWords = words.Skip(4);
foreach (var word in skipFirstFourWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
//OUTPUT:
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 2

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };
var skipFirstFiveNumbers = numbers.Skip(5);
foreach (var number in skipFirstFiveNumbers)
{
    Console.WriteLine(number);
}
Console.ReadKey();
//OUTPUT:
//5
//4
//1
//3
//0

Example 3

Skip and SkipWhile operator do not support in query syntax but still we can use skip and skip on query variable. Consider the example given below, we need to skip 2 words from first 4 words whose length is greater than 4.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };

var stringNumbers = from s in words
                              where s.Length > 4 // find words whose length is grater than 4
                              select s;

Console.WriteLine("words whose length is grater than 4");
foreach (var word in stringNumbers)
{
    Console.WriteLine(word);
}
/*
OUTPUT:
Three
Eight
Seven
*/

var skipFirstTwoWords = stringNumbers.Skip(2); //skip first 2 words
Console.WriteLine("After skipping two words");
foreach (var word in skipFirstTwoWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
/*
OUTPUT:
Seven
*/

Example 4

In this example, we will use two List object of type Employee and Department as shown below. Here, we need to skip first 2 employees of Department 'IT' using query syntax. It is similar to Example 3.

 class Program
 {
     class Employee
     {
         public int Id { get; set; }
         public string Name { get; set; }
         public int Salary { get; set; }
         public int DeptId { get; set; }
     }
     class Department
     {
         public int Id { get; set; }
         public string Name { get; set; }
     }
     static void Main(string[] args)
     {
         // list of type Employee
         List<Employee> employee = new List<Employee>(){
             new Employee { Id=1, Name = "Rahul", Salary=50000, DeptId=101},
             new Employee { Id=2, Name = "John", Salary=10000, DeptId=102},
             new Employee { Id=3, Name = "Mike", Salary=4000, DeptId=103},
             new Employee { Id=4, Name = "Mary", Salary=75000, DeptId=101},
             new Employee { Id=5, Name = "Sachin", Salary=6500, DeptId=102},
             new Employee { Id=6, Name = "Deepak", Salary=80000, DeptId=103},
             new Employee { Id=7, Name = "Mithoon", Salary=10000, DeptId=101},
             new Employee { Id=8, Name = "Hrithik", Salary=72000, DeptId=102},
             new Employee { Id=9, Name = "Savio", Salary=10000, DeptId=103},
             new Employee { Id=10, Name = "Yogesh", Salary=90000, DeptId=101}
         };
         // list of type Department
         List<Department> department = new List<Department>(){
             new Department { Id=101, Name = "IT"},
             new Department { Id=102, Name = "HR"}, 
             new Department { Id=103, Name = "Payroll"}, 
             new Department { Id=104, Name = "Sales"}, 
             new Department { Id=105, Name = "Production"},
         };

         var data = from e in employee
                    join d in department
                    on e.DeptId equals d.Id
                    where d.Name == "IT"
                    select new
                    {
                        eId = e.Id,
                        eName = e.Name,
                        dName = d.Name
                    };
         Console.WriteLine("---------All employees in department IT---------");
         foreach (var v in data)
         {
             Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
         }

         Console.WriteLine("---------Now skip first two employees in department IT---------");
         var afterSkip = data.Skip(2);
         foreach (var v in afterSkip)
         {
             Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
         }
         Console.ReadKey();

         //OUTPUT:
         //---------All employees in department IT---------
         //Employee Id - 1, Employee Name - Rahul, Department Name - IT
         //Employee Id - 4, Employee Name - Mary, Department Name - IT
         //Employee Id - 7, Employee Name - Mithoon, Department Name - IT
         //Employee Id - 10, Employee Name - Yogesh, Department Name - IT
         //---------Now skip first two employees in department IT---------
         //Employee Id - 7, Employee Name - Mithoon, Department Name - IT
         //Employee Id - 10, Employee Name - Yogesh, Department Name - IT
     }
 }

Using SkipWhile Partitioning Operator In LINQ

Example 1

Let's understand SkipWhile operator with example. Consider the string array of words given below. Here first 3 elements are "Five", "Four", "One" and their length is less than 5, so according to SkipWhile definition, first 3 elements satisfy condition and condition becomes true but from 4th element that is "Three" here length is equal to 5 that means if length is equal to 5 then condition becomes false, so SkipWhile will return remaining operator once condition is false.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length < 5           true     true     true     false
var data = words.SkipWhile(x => x.Length < 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Three
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 2

Here, we will use same example as shown above, in above example we used (<) less than operator, now we will use (>) greater than operator. Here the first element is "Five" whose length is equal to 4, but it is less than 5, so condition becomes false at first element only because we are checking for element whose length is greater than 5, so according to definition, it will returns remaining element from element where condition become false.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length > 5           false    
var data = words.SkipWhile(x => x.Length > 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Five
//Four
//One
//Three
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 3

Here, in below example first 5 elements when divided by 5, they have some Remainder but from 6th element that is '5' which has Remainder 0, here the condition becomes false because we are checking for Remainder should not be equal to zero, so it will return all the remaining elements from 6th element.

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };

var data = numbers.SkipWhile(x => x % 5 != 0);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//5
//4
//1
//3
//0

Using SkipWhile With Index

Example 1

We can use, second overload of SkipWhile. It passes index of each elements. In below example, it skips all the element till the length of elements is greater than it's index. Here, condition becomes false at 5th element("Nine"), so it will return remaining elements.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
// length is              4         4         3         5           4         5         3         5           3         4
// index  is              0         1         2         3           4         5         6         7           8         9
// length > index   true     true     true     true       false      -         -          -            -          -
var data = words.SkipWhile((x,i) => x.Length > i);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 4

In this example, we will use two List object of type Employee and Department as used in Example 4 of Skip Operator. Here, we will fetch all employees of Department 'IT' using query syntax.

var data = from e in employee
           join d in department
           on e.DeptId equals d.Id
           where d.Name == "IT"
           select new
           {
               eId = e.Id,
               eName = e.Name,
               dName = d.Name
           };
Console.WriteLine("---------All employees in department IT---------");
foreach (var v in data)
{
    Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
}
//OUTPUT:
//---------All employees in department IT---------
//Employee Id - 1, Employee Name - Rahul, Department Name - IT
//Employee Id - 4, Employee Name - Mary, Department Name - IT
//Employee Id - 7, Employee Name - Mithoon, Department Name - IT
//Employee Id - 10, Employee Name - Yogesh, Department Name - IT

Now, we will apply SkipWhile operator on Name column whose length is greater than 4. Here in above output Employee Name - Rahul , Rahul has length greater than 4, so condition is true here, but for Mary length is not greater than 4, so condition becomes false here.

Console.WriteLine("---------Now use SkipWhile on Name column---------");
var afterSkipWhile = data.SkipWhile(x => x.eName.Length > 4);
foreach (var v in afterSkipWhile)
{
    Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
}
Console.ReadKey();
//---------Now use SkipWhile on Name column---------
//Employee Id - 4, Employee Name - Mary, Department Name - IT
//Employee Id - 7, Employee Name - Mithoon, Department Name - IT
//Employee Id - 10, Employee Name - Yogesh, Department Name - IT
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON