Skip Operator Part 7

Skip is one of the filtering operators available in linq. Skip operator skips the first count elements and returns rest of the elements in the collection. The prototype of the skip operator looks something like this

public static IEnumerable<T> Skip<T>(
this IEnumerable<T> source,
int count);

 

Looking at the prototype, you will notice that it is an extension method that is applied on any object that implements IEnumerable<T>. It takes an integer that specifies how many elements to skip before it starts to return rest of the elements in the collection. If the number of elements to skip is greater than count of elements in the collection, you will get an output sequence that will be an empty collection.

image

CWindowssystem32cmd.exe

In the above example we are skipping the first 3 elements and returning the rest of the elements from the input sequence. Let's change the above example to skip all the elements from the collection by by passing an integer which is greater than the size of the input collection.

image 

CWindowssystem32cmd.exe

I have modified the above example to skip the entire collection by passing an integer which is equal to the size of the input collection. This results in an empty collection. I spiced up the example by adding another operator which actually allows you to return a default value when the collection is empty. Hence you can see in the output the result is -1.

So far we have only looked at example of using skip operator with linq to object. Let's see an example of using skip operator with linq to SQL and see how it gets translated into SQL statement.

image

CWindowssystem32cmd.exe (2)

From the above example, you would notice that skip operator gets translated into row_number function in linq to sql and than a where clause gets applied to show only rows that are greater than the number returned by the row_number function.

image

CWindowssystem32cmd.exe

 

In the above example we are making use of the skip operator with linq to xml. I am first getting all the persons using the descendants operator and then using the skip operator i skip the first element. I then convert the xml element into anonymous type containing FirstName and LastName. From the result you can see I am displaying the firstname of the of the last person in the collection.

No Comments