How to Use LINQ Skip and Take in C# for Data Paging
In C#, use
Skip(n) to bypass the first n elements of a collection and Take(m) to select the next m elements. Together, they help you extract a specific range of items from a list, commonly used for paging through data.Syntax
The Skip and Take methods are LINQ extension methods used on collections like arrays or lists.
Skip(int count): Skips the firstcountelements.Take(int count): Takes the nextcountelements after skipping.
They can be chained to select a specific segment of a collection.
csharp
var subset = collection.Skip(n).Take(m);Example
This example shows how to get items 4 to 6 from a list of numbers using Skip and Take.
csharp
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = Enumerable.Range(1, 10).ToList(); // Skip first 3 numbers, then take next 3 var subset = numbers.Skip(3).Take(3); foreach (var num in subset) { Console.WriteLine(num); } } }
Output
4
5
6
Common Pitfalls
Common mistakes when using Skip and Take include:
- Skipping more elements than the collection has, which results in an empty sequence.
- Taking more elements than remain after skipping, which returns fewer elements than requested but does not cause errors.
- Forgetting that
SkipandTakedo not modify the original collection but return a new sequence.
csharp
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> {1, 2, 3}; // Wrong: Skipping more than count returns empty var empty = numbers.Skip(5).Take(2); Console.WriteLine("Count after skip 5 and take 2: " + empty.Count()); // Correct: Skip within range var subset = numbers.Skip(1).Take(2); Console.WriteLine("Subset elements:"); foreach (var num in subset) { Console.WriteLine(num); } } }
Output
Count after skip 5 and take 2: 0
Subset elements:
2
3
Quick Reference
| Method | Description | Example |
|---|---|---|
| Skip(int count) | Skips the first 'count' elements | collection.Skip(3) |
| Take(int count) | Takes the next 'count' elements | collection.Take(5) |
| Skip + Take | Selects a range by skipping then taking | collection.Skip(10).Take(5) |
Key Takeaways
Use Skip(n) to ignore the first n elements of a collection.
Use Take(m) to select the next m elements after skipping.
Skip and Take together help extract specific ranges, useful for paging.
They return new sequences and do not change the original collection.
Skipping beyond the collection size returns an empty sequence without error.