+92 332 4229 857 99ProjectIdeas@Gmail.com

LINQ TakeWhile() Method (C#.net)




LINQ TakeWhile() Method (C#.net):
The following code shows you how to apply some condition on array and taking those elements. For example array contains {2,3,4,7,8} and you want all those elements which are odd then applying LINQ TakeWhile() method you can do this although there is another way. But through this see the code below.

Code

int[] array = { 5, 3, 9, 8, 10 };

IEnumerable<int> query =
           array.TakeWhile(x => x % 2 != 0);

      foreach (var item in query)
          Console.Write(item + " ");

Output of the program is:
5 3 9 (because these three are odd)


Another Example: 
string[] array = {"maryam","saad","zainab","osama","bilal"};

IEnumerable<string> query =
           array.TakeWhile(a => string.Compare("zainab", a, true) != 0);

     foreach (var item in query)
         Console.Write(item + " ");

Output of the program is:


maryam saad (if find "zainab" print all previous elements)  



1 comments:

de said...

The TakeWhile method invokes the delegate method (selector method) for each value in the input sequence. While invoking, the TakeWhile method passes the corresponding value to the delegate method TSource input parameter. The delegate executes and checks the condition. This method determines elements until the selector method returns false. The predicate method receives one element at a time from the input sequence and returns whether the element should be included in the output sequence.

prathap
Dot Net Training in Chennai