Freigeben über


Generic queryable example ( Query Design continued ):

This post is a part of a series of posts about query design. For the previous post see: https://blogs.msdn.com/vladimirsadov/archive/2007/06/07/query-pattern-composability-query-design-continued.aspx

 

Here is another example of a queryable collection. In this case we have a collection that is generic so it can be used with elements of different types. What is more interesting is that MyGenericQueryable can be used with query projections that change type of the element.

                ****

Public Delegate Function SelectorDelegate(Of T, S)(ByVal arg As T) As S

Class MyGenericQueryable(Of T)

    Public elements() As T

    Public Function [Select](Of S)(ByVal projection As SelectorDelegate(Of T, S)) As MyGenericQueryable(Of S)

        Dim new_col As New MyGenericQueryable(Of S)

        Dim new_elements(elements.Length - 1) As S

        new_col.elements = new_elements

        For I As Integer = 0 To elements.Length - 1

     new_col.elements(I) = projection(elements(I))

        Next

        Return new_col

    End Function

End Class

Module Module1

    Sub Main()

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

        Dim col As New MyGenericQueryable(Of Integer)

        col.elements = arr

        'note that the projection produces an element of a different type

        'while col contains integer elements, q contains strings

        Dim q = From i In col Select i_string = i.ToString

        For Each t In q.elements

            Console.WriteLine(t)

        Next

    End Sub

End Module

Comments