Skip to main content

First - Simple

This sample uses First to return the first matching element as a Product, instead of as a sequence containing a Product.

Public Sub Linq58()
    Dim products = GetProductList()

    Dim product12 = From p In products _
        Where p.ProductID = 12 Take 1

    ObjectDumper.Write(product12)
End Sub


Public Function GetProductList() As List(Of Product)
    If productList Is Nothing Then
        CreateLists()
    End If

    Return productList
End Function

Result:
ProductID=12 ProductName=Queso Manchego La Pastora Category=Dairy Products UnitPrice=38 UnitsInStock=86


First - Condition

This sample uses First to find the first element in the array that starts with 'o'.

Public Sub Linq59()

    Dim strings = New String() {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}

    Dim FirstO = strings.First(Function(s) s(0) = "o"c)

    Console.WriteLine("A string starting with 'o': " & FirstO)
    
End Sub

Result:
A string starting with 'o': one


FirstOrDefault - Simple

This sample uses FirstOrDefault to try to return the first element of the sequence, unless there are no elements, in which case the default value for that type is returned.

Public Sub Linq61()
    Dim numbers As Integer() = {}

    Dim firstNumOrDefault = numbers.FirstOrDefault()

    Console.WriteLine(firstNumOrDefault)
End Sub

Result:
0


FirstOrDefault - Condition

This sample uses FirstOrDefault to return the first product whose ProductID is 789 as a single Product object, unless there is no match, in which case null is returned.

Public Sub Linq62()
    Dim products = GetProductList()

    Dim product789 = products.FirstOrDefault(Function(p) p.ProductID = 789)

    Console.WriteLine("Product 789 exists: {0}", product789 IsNot Nothing)
End Sub

Result:
Product 789 exists: False


ElementAt

This sample uses ElementAt to retrieve the second number greater than 5 from an array.

Public Sub Linq64()
    Dim numbers() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}

    Dim fourthLowNum = (From n In numbers _
        Where n > 5 _
        Select n).ElementAt(1)  ' second number is index 1 because sequences use 0-based indexing

    Console.WriteLine("Second number > 5: " & fourthLowNum)
End Sub

Result:
Second number > 5: 8