Skip to main content

LINQ Query Samples - Conversion Operators


ToArray

This sample uses ToArray to immediately evaluate a sequence into an array.

Public Sub Linq54()
    Dim doubles() = {1.7, 2.3, 1.9, 4.1, 2.9}

    Dim sortedDoubles = From d In doubles _
        Select d _
        Order By d Descending

    Dim doublesArray = sortedDoubles.ToArray()

    Console.WriteLine("Every other double from highest to lowest:")
    For d As Integer = 0 To doublesArray.Length
        Console.WriteLine(doublesArray(d))
        d += 1
    Next
End Sub

Result:
Every other double from highest to lowest:
4.1
2.3
1.7


ToList

This sample uses ToList to immediately evaluate a sequence into a List(Of T).

Public Sub Linq55()
    Dim words() = {"cherry", "apple", "blueberry"}

    Dim sortedWords = From w In words _
        Select w _
        Order By w

    Dim wordList = sortedWords.ToList()

    Console.WriteLine("The sorted word list:")
    For Each w In wordList
        Console.WriteLine(w)
    Next
End Sub

Result:
The sorted word list:
apple
blueberry
cherry


ToDictionary

This sample uses ToDictionary to immediately evaluate a sequence and a related key expression into a dictionary.

Public Sub Linq56()
    Dim scoreRecords() = {New With {.Name = "Alice", .Score = 50}, _
                          New With {.Name = "Bob", .Score = 40}, _
                          New With {.Name = "Cathy", .Score = 45}}

    Dim scoreRecordsDict = scoreRecords.ToDictionary(Function(sr) sr.Name)

    Console.WriteLine("Bob's score: {0}", scoreRecordsDict("Bob"))

End Sub

Result:
Bob's score: { Name = Bob, Score = 40 }


OfType

This sample uses OfType to return only the elements of the array that are of type double.

Public Sub Linq57()
    Dim numbers() = {Nothing, 1.0, "two", 3, "four", 5, "six", 7.0}

    Dim doubles = From n In numbers _
        Where TypeOf n Is Double _
        Select n

    Console.WriteLine("Numbers stored as doubles:")
    For Each d In doubles
        Console.WriteLine(d)
    Next
End Sub

Result:
Numbers stored as doubles:
1
7