Using LINQ Skip to Select Specific Data

Using LINQ Skip to Select Specific Data

linq

14 Articles

Improve

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.

Table of Contents

  1. Introduction
  2. Perform partition using Skip
  3. Perform partition using SkipWhile
  4. Summary

Introduction

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.

Perform partition using Skip

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.

Code Sample - LINQ Skip

Demo - LINQ Skip Clause Demo

Let's try LINQ Skip

  • We have Product class with following properties - Id, Name, Color, Price, Size
  • Enter the number of products you would like to list.
  • Click on Skip Products
  • Click on reset to try other combination
Id Name Color Price Size
1 HL Road Frame Black 1000 58
2 HL Road Frame Red 1000 58
3 HL Road Frame Black 1000 58
4 HL Road Frame Red 1000 58
5 HL Road Frame Brown 1000 58
6 HL Road Frame White 1000 58

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.

Code Sample - LINQ SkipWhile

Demo - LINQ SkipWhile Clause Demo

Let's try LINQ SkipWhile

  • We have Product class with following properties - Id, Name, Color, Price, Size
  • Enter the condition based on which you like to select.
  • Click on SkipWhile Products
  • Click on reset to try other combination
Id Name Color Price Size
1 HL Road Frame Black 1000 58
2 HL Road Frame Red 1000 58
3 HL Road Frame Black 1000 58
4 HL Road Frame Red 1000 58
5 HL Road Frame Brown 1000 58
6 HL Road Frame White 1000 58

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.

  • Linq
  • Skip
  • SkipWhile
  • Partition