Projecting in more details (single, multiple items, anonymous types)

One interesting aspect of VB queries is that you can select multiple values. When you do this, the values get combined into an anonymous type. “Anonymous types” is a new feature for VB9. Essentially an anonymous type is a class that contains one or more named values. Compiler simply generates an anonymous type with number, type and names of contained values matching the variables produced by the selector. Here is a simple example:

 

Module Module1

    Sub Main()

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

        Dim q = From n In arr Select num = n, square = n ^ 2

        For Each record In q

            Console.WriteLine(record)

        Next

    End Sub

End Module

 

The output:

{ num = 1, square = 1 }

{ num = 2, square = 4 }

{ num = 3, square = 9 }

{ num = 4, square = 16 }

 

 

The values that are combined into an anonymous type do not need to be defined in the same operator. As long as you have more than one iteration variable at the end of the query, they will be parts of composite element of resulting sequence. Explicit Select-ing is not required. Example:

 

Module Module1

    Sub Main()

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

        Dim arr2() As String = {"a", "b", "c"}

        ' this query defines control variable n

        ' then (after filtering) it adds variable k

        ' and does more filtering

        ' at the end we have both n and k variables visible

        Dim q = From n In arr1 _

                Where n > 1 _

                From k In arr2 _

                Where (k <> "b")

        For Each record In q

            Console.WriteLine(record)

        Next

    End Sub

End Module

 

Output:

{ n = 2, k = a }

{ n = 2, k = c }

{ n = 3, k = a }

{ n = 3, k = c }

{ n = 4, k = a }

{ n = 4, k = c }