First Query Operator in LINQ using VB.NET

This article defines the basic use of First operator in Linq.
  • 3055

First Operator

The First operator returns the first element in a sequence that satisfies a specified condition. If there is no first elements in the sequence (or no first element that passes the predicate function), use the FirstOrDefault operator instead.

Understanding First

The below defines the numbers can be an array of integer numbers.

Here is an example of numbers.

Dim numbers As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

 

Now using First operator

 

Dim numbers As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

Dim first As Integer = numbers.First()

 

For example

 

Module Module1

    Sub Main()

        Dim numbers As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

        Dim first As Integer = numbers.First()

        Console.WriteLine("The first number is: " & first)

    End Sub

End Module

 

OUTPUT
 

f1.gif
 

 

Now find out the first even number from the above integer number list.

 

For Example

 

Module Module1

    Sub Main()

        Dim numbers As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

        Dim firstEven As Integer = numbers.First(Function(n) n Mod 2 = 0)

        Console.WriteLine("The first even number is " & firstEven)

    End Sub

End Module

 

OUTPUT

 

f3.gif

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.