SkipWhile

In this chapter you will learn:

  1. How to use SkipWhile operator
  2. SkipWhile with filter delegate
  3. SkipWhile and logic operator
  4. Filter by index

Get to know SkipWhile operator

SkipWhile enumerates the input sequence, ignoring each item until the given predicate is false.

It then emits the remaining elements:

using System;/*from j  a  va 2 s .co m*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 3, 5, 2, 7, 4, 1 };

        var skipWhileSmall = numbers.SkipWhile(n => n < 5);
          
        foreach(int s in skipWhileSmall){
           Console.WriteLine(s);
        }
    }
}

The output:

SkipWhile with filter delegate

using System;/* ja v  a  2s  . c o  m*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] names = { "Java", "C#", "Javascript", "SQL", 
          "Oracle", "Python", "C++", "C", "HTML", "CSS" };

        IEnumerable<string> query = names.SkipWhile(n => n.Length < 5);
        foreach(String s in query){
           Console.WriteLine(s);
        }
    }
}

The output:

SkipWhile and logic operator

using System;//from ja  v  a 2  s . com
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
    public static void Main() {
        string[] presidents = {"ant", "arding", "arrison", "Hayes", "Hoover", "ackson"};
        IEnumerable<string> items = presidents.SkipWhile((s, i) => s.Length > 4 && i < 10);
        foreach (string item in items)
            Console.WriteLine(item);
    }
}

Filter by index

using System;/*from   jav  a2 s  .c om*/
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class MainClass{
   public static void Main() {

       int[] numbers = { 5, 4, 8, 6, 7, 2, 0 };
       
       var laterNumbers = numbers.SkipWhile((n, index) => n >= index);
       
       Console.WriteLine("All elements starting from first element less than its position:");
       foreach (var n in laterNumbers) {
           Console.WriteLine(n);
       }
   }

}

Next chapter...

What you will learn in the next chapter:

  1. How to use Sum operator
  2. Sum the total length of strings
  3. Sum custom types
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip