Skip and Select Elements in a String Array using LINQ

Here’s how to skip and select elements in a string array using LINQ. In the example shown below, we will skip the first two elements of an array and select the next three.

C#

static void Main(string[] args)
{
string[] arr = {"One", "Two", "Three",
"Four", "Five", "Six",
"Seven", "Eight"};
var result = from x in arr
.Skip<string>(2)
.Take<string>(3)
select x;

foreach (string str in result)
{
Console.WriteLine("{0}", str);
}

Console.ReadLine();
}

VB.NET

Sub Main(ByVal args() As String)
Dim arr() As String = {"One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight"}
Dim result = From x In arr.Skip(Of String)(2).Take(Of String)(3)
Select x

For Each str As String In result
Console.WriteLine("{0}", str)
Next str

Console.ReadLine()
End Sub

OUTPUT

Three
Four
Five



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: