Take While Operator Part 6

Takewhile is a partitioning operator available in linq. It starts from the beginning of the series and continues to return the elements from the input sequence as long as condition is validating to true. As soon as it hits the first statement that evaluates to false it skips rest of the collection.

Here is how the TakeWhile prototype looks like

public static IEnumerable<T> TakeWhile<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

Looking at the prototype, we can see that TakWhile is an extension method that is extending any object that implements IEnumerable<T>. It takes in a delegate that gets evaluated on every object that gets passed through when the collection gets enumerated. If the object being passed gets evaluated to true condition it gets added to the output sequence. Once the predicate returns false, it stops evaluating rest of the elements in the input sequence.

Let's look at a simple example of TakeWhile operator.

image

CWindowssystem32cmd.exe

Although one might expect the result to contain all the numbers less than  5, however that is not the case. The reason for this is, in the collection the first element right after 4 is 6. Since 6 is greater than 5, the process short circuits immediately. However if we truly want to get the right numbers in the output sequence we can sort the collection first and than use the takewhile operator. Let's modify the above example and see the results.

image

CWindowssystem32cmd.exe

Looking at the result you would notice that this time all the correct numbers are returned because we sorted the collection first and than applied the takewhile which allowed us to get all the correct numbers from the input sequence.

Another point worth mentioning is, takewhile operator is a differed query operator which means that query will not execute until you iterate over the query. This means that every time you change the collection and run the query, it would re-execute and include new data in its execution. Let's look at an example of that.

image

CWindowssystem32cmd.exe (2)

From the above result, you would notice that the new modification in the collection is reflected when we iterate over the collection, the second time. This shows that query is differed and it does not get executed unless you iterate.

TakeWhile operator applies to linq to objects and linq to xml. It does not have any direct translation in linq to sql. Therefore using takewhile operator for linq to sql queries will crash because sql server QueryProvider would not be able to translate those linq queries into appropriate sql queries to be executed on sql server.

No Comments