LINQ FirstOrDefault and LastOrDefault operator in VB.NET

This article defines the basic use of FirstOrDefault and LastOrDefault operator in LINQ.
  • 3655

FirstOrDefault operator

The FirstOrDefault operator returns the first element of a sequence, or a default value if no element is found.

Example1

This example defines the FirstOrDefault operator with a integer array without element then it will return 0 value.

Module Module1

    Sub Main()

        Dim numbers() As Integer = {}

        Dim first As Integer = numbers.FirstOrDefault()

        MsgBox(first)

    End Sub

End Module

 

OUTPUT
 

fofd1.gif
 

 Example2
 

This example defines the FirstOrDefault operator with a integer array with some element in the array then it will return the first value.

 

Module Module1

    Sub Main()

        Dim numbers() As Integer = {1, 2, 3}

        Dim first As Integer = numbers.FirstOrDefault()

        MsgBox(first)

    End Sub

End Module

 

OUTPUT
 

fofd2.gif
 

 Example 3

 

Module Module1

    Sub Main()

        Dim numbers As Integer() = {1, 3, 5, 7, 9}

        Dim query = numbers.FirstOrDefault(Function(n) n Mod 2 = 0)

        MsgBox("The first even element in the sequence:" & query)

    End Sub

End Module

 

OUTPUT

 
fofd3.gif
 

LastOrDefault operator

 

The LastOrDefault operator returns the last element of a sequence, or a default value if no element is found.

 

For example

 

Module Module1

    Sub Main()

        Dim numbers As Integer() = {1, 3, 5, 7, 9}

        Dim query = numbers.FirstOrDefault(Function(n) n Mod 2 = 0)

        query = numbers.LastOrDefault(Function(n) n Mod 2 = 1)

        MsgBox("The last odd element in the sequence:" & query)

    End Sub

End Module

 

OUTPUT
 

fofd4.gif

Categories

More Articles

© 2013 dotNetheaven. All rights reserved.