SkipWhile Operator Part 8
SkipWhile Operator skips elements based on the delegate condition. It continues to skip the elements as long as the predicate returns true. As soon as it encounters false statement, it returns rest of the elements. The prototype of the skip operator looks like this
public static IEnumerable<T> SkipWhile<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);
From the prototype you would notice that skipwhile is an extension method that is applied on all objects that implement IEnumerable<T>. It takes a predicate that gets executed on every element that gets iterated on the input sequence. If predicate returns true, it skips the element until it evaluates to false; after which it returns rest of the collection. SkipWhile operator has a second prototype which looks like this
public static IEnumerable<T> SkipWhile<T>(
this IEnumerable<T> source,
Func<T, int, bool> predicate);
In the above SkipWhile operator, the predicate gets passed the index of the element in the source collection.
From the above result, you would notice that we are first ordering the results. Then we apply the skipwhile operator to skip all the elements which are less than 5 and than returning rest of the elements. From the output you would notice that our output sequence contains all the elements that are greater than or equal to 5.
The above example we have seen, made use of skip operator with linq to objects. SkipWhile operator has no direct conversion with linq to sql. Therefore you have to apply another operator called AsEnumerable to hint the compiler that you want to execute this part of the query in memory instead of sending the entire query to database which would result in failure since linq to sql cannot convert skipwhile operator to an operator in sql which sql server can understand. Let's look at an example.
In the above example we have a mixture of both linq to sql and linq to objects. We are first querying the database for customers. Than in order to apply skip while operator which cannot be translated to appropriate sql statement by linq to sql provider, we make use of AsEnumerable operator to tell the compiler that we want to perform this part of the query in the memory. After that we make use of the skipwhile operator to skip all the customers whose order's sum is greater than 1000 dollars.
skipwhile operator can also be used with linq to xml to skip elements as long as a condition is not met.
In the above example we are making use of skipwhile operator with linq to xml. Using the descendants property, we grab all the Names from the query and we than apply the skipwhile operator passing in the lambda expression which checks to see if the name starts with A. So it skips all the elements that starts with A, resulting in the last element which returns Scott.