Linq Example 11 : Skip While

4:33 AM
Linq Query:

int[] numbers = { 5, 4, 1, 3, 1, 1, 1, 1, 1, 1 };
            
            var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);

            Console.WriteLine("All elements starting from first element divisible by 3:");
            foreach (var n in allButFirst3Numbers)
            {
                Console.WriteLine(n);
            }


Output:

3
1
1
1
1
1
1

Explanation: 
  • The only number here divisble by 3 is 3 at position four in numbers.
  • We will start from 5  and skip it as it is no divisible by 3.
  • Next skip 4,1 
  • Now its 3. we will add it to allButFirst3Numbers.. 
  • Now from now on all the number will be added to the allButFirst3Numbers.. As the name SkipWhile suggest.. we will skip until a number that is divisible by 3 is encountered. after that all the numbers will be added regardless of the condition.


0 comments:

Post a Comment