C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Step 1: In this example, the integer array is allocated and immediately filled with six 32-bit signed integers.
Step 2: The argument to Skip is the int 2. This will pass over the first two elements and only return those that follow.
Step 3: The argument here is 4. The second loop in the example repeats this procedure but for 4 elements.
Info: No action is taken until you loop over the resulting variable. Skip() takes effect when the foreach queries for results.
ForeachC# program that uses Skip method from LINQ
using System;
using System.Linq;
class Program
{
static void Main()
{
// Step 1: create array for demonstration.
int[] array = { 1, 3, 5, 7, 9, 11 };
// Step 2: get collection of all elements except first two.
var items1 = array.Skip(2);
foreach (var value in items1)
{
Console.WriteLine("SKIP 2: {0}", value);
}
// Step 3: call Skip again but skip the first 4 elements.
var items2 = array.Skip(4);
foreach (var value in items2)
{
Console.WriteLine("SKIP 4: {0}", value);
}
}
}
Output
SKIP 2: 5
SKIP 2: 7
SKIP 2: 9
SKIP 2: 11
SKIP 4: 9
SKIP 4: 11
Start: We declare an array that has several values in it. The first 3 elements are less than 10.
And: We call SkipWhile with a Func that returns true for elements less than 10. The first 3 elements in the array are skipped.
C# program that shows SkipWhile method
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] array = { 1, 3, 5, 10, 20 };
var result = array.SkipWhile(element => element < 10);
foreach (int value in result)
{
Console.WriteLine(value);
}
}
}
Output
10
20
Tip: You could use SkipWhile. Then you could call ToArray to ToList to convert the IEnumerable back into an array or List.
ToArrayToListArrayListInfo: The Skip extension method internally allocates a new class that is compiler-generated and stores the state of the Skip operation.
Tip: This indicates that using a for-loop and starting at the desired index will be much faster.
ForTip 2: Often you would use Skip on a collection that cannot be accessed by specific indexes.
Note: The Take extension method specifies that you only want to access the following several elements.
So: If you want the middle elements in a sequence, you can Skip over the first several and then Take the part you want.