LINQ channel icon LINQ · 26 published articles

Using LINQ Skip to Select Specific Data

In this post I will teach you how to select specific data within collections using LINQ in .NET. All with live working demo.

Using LINQ Skip to Select Specific Data
On this page

What you'll learn

In this article, let's learn about how to use Skip and SkipWhile in LINQ in .NET.

Note: If you have not done so already, I recommend you read the article on Using LINQ Take to Select Specific Data in Collections.

We can perform skip and select specific piece of data from beginning of a collection using LINQ. We're going to use Skip() and SkipWhile() methods. Let's take a look at each of these methods and how they work.

Why it matters

When listing the items, its not always possible to list all the items. Sometimes we need to limit and partition the items from database or need a pagination in UI to display subset of records for better UX (User Experience) as not all the datas are required everytime unless its a reporting task. So Skip(n) allows you to skip specific items from beginning of collection. It skips number of items given as input and returns records after that number.

Implementation

Perform partition using Skip

C#


List<Product> products = GetProducts();

//Method Syntax
List<Product> partitionedProducts = products
                                    .Skip(2)
                                    .ToList();
                    
//Query Syntax
List<Product> partitionedProducts = (from product in products select product)
                                    .Skip(2)
                                    .ToList();
        
Live demo: LINQ Skip Clause Demo — interactive controls are available when the page loads.

Perform conditional partition using SkipWhile

We can also extract data conditionally using SkipWhile while the condition evaluates to true. Note that Enumeration stops when the predicate function returns false for an element or when source contains no more elements.

C#


List<Product> products = GetProducts();

//Method Syntax
List<Product> partitionedProducts = products
                                    .SkipWhile(product => product.Name.StartsWith("P"))
                                    .ToList();
                    
//Query Syntax
List<Product> partitionedProducts = (from product in products select product)
                                    .SkipWhile(product => product.Name.StartsWith("P"))
                                    .ToList();
        
Live demo: LINQ SkipWhile Clause Demo — interactive controls are available when the page loads.

Summary

In this article we learn't how to locate partition and extract specific data within collection using Skip and SkipWhile. We also saw how we can pass an condition to partition data. Skip() can be used together with Take() to implement pagination. All these can be used with any IEnumerable or IQueryable types.