VB.Net program to demonstrate the FirstOrDefault() LINQ extension method

Here, we are going to demonstrate the FirstOrDefault() LINQ extension method in VB.Net.
Submitted by Nidhi, on January 24, 2021 [Last updated : March 08, 2023]

VB.Net – FirstOrDefault() LINQ Extension Method

In this program, we will use FirstOrDefault() LINQ method to print the first value of the array, if an array is empty then it will print the default value on the console screen.

Program/Source Code:

The source code to demonstrate the FirstOrDefault() LINQ extension method is given below. The given program is compiled and executed successfully.

VB.Net code to demonstrate the example of FirstOrDefault() LINQ extension method

'VB.NET program to demonstrate the 
'FirstOrDefault() LINQ extension method.

Imports System
Imports System.IO
Imports System.Linq

Module Module1
    Sub Main()
        Dim intVals() As Integer = {50, 20, 40, 35, 10, 27, 60}

        Dim val = intVals.FirstOrDefault()
        Console.WriteLine("First Value: {0}", val)

        intVals = {}

        val = intVals.FirstOrDefault()
        Console.WriteLine("Default Value: {0}", val)
    End Sub
End Module

Output

First Value: 50
Default Value: 0
Press any key to continue . . .

Explanation

In the above program, we created a module Module1 that contains the Main() function. The Main() function is the entry point for the program.

In the Main() function, we created an integer array that contains 7 elements. Here, we used FirstOrDefault() LINQ extension method to print the first element of the array, if an array is empty then the default value will be printed on the console screen.

VB.Net LINQ Query Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.