Sunday, August 23, 2020

Partitioning Operator: Take & TakeWhile

In LINQ, Partition Operators are used for separating the given sequence into two portions without

Sorting the element and return the one of the portions


Method

Description

Take

This operator is used fetch the first “n” number of elements from the data source where “n” is integer which is passed as a parameter to the Take method.

TakeWhile

This operator behaves similarly to the take() method except that instead of taking the first “n” element of sequence , It takes all of initial elements of sequence that meet the criteria specified by the predicate, and stops on the first element that doesn’t meet the criteria

 

Example: Take() Method – C#

 

IList<string> strList = new List<string>(){ "One", "Two", "Three" };
 
var newList = strList.Take(2);
 
foreach(var str in newList)
    Console.WriteLine(str);

 

 

Output -

One

Two

 

Example: TakeWhile() Method – C#

 
IList<string> strList = new List<string>() { 
                                            "Three", 
                                            "Four", 
                                            "Five", 
                                            "Hundred"  };
 
var result = strList.TakeWhile(s => s.Length > 4);
 
foreach(string str in result)
        Console.WriteLine(str);

 


Output -

Three


No comments:

Post a Comment