12.6. Summary

In order to draw together the points you have seen in this chapter, let's go back to an early example in which we were projecting the first name and age properties from the people collection into a newly created list. The following extension method enables us to not only supply a predicate for determining which objects to select, but also to specify a function for doing the output projection.

<System.Runtime.CompilerServices.Extension()> _
Public Function Retrieve(Of TInput, TResult)( _
                                     ByVal source As IEnumerable(Of TInput), _
                                     ByVal predicate As Func(Of TInput, Boolean), _
                                     ByVal projection As Func(Of TInput, TResult) _
                                             ) As IEnumerable(Of TResult)
    Dim outList As New List(Of TResult)
    For Each inputValue In source
        If predicate(inputValue) Then outList.Add(projection(inputValue))
    Next
    Return outList
End Function

Note that in this example we have been able to keep all the parameters, both input and output, generic enough that the method can be used across a wide range of IEnumerable collections and lists. When this method is invoked, we use the expressive power of extension methods so that it appears as an instance method on the people collection. As you saw earlier, we could chain the output of this method with another extension method for an IEnumerable object.

Dim peopleAges = people.Retrieve( _
     Function(inp As Person) inp.Age > 40, _
     Function(outp As Person) New With {.Name = outp.FirstName, outp.Age} _
                                  )

To determine which Person objects to return, a simple lambda function checks if the age is greater than 40. Interestingly, we use an anonymous type in the lambda function to project from a Person to the name-age duple. Doing this also requires the compiler to use type inferencing to determine the resulting IEnumerable, peopleAges — the contents of this IEnumerable all have properties Name (String) and Age (Integer).

Through this chapter you have seen a number of language improvements, syntactical shortcuts that contribute to the objective of creating expression trees that can be invoked. This is the foundation on which Linq is based. You will see significant improvements in your ability to query data wherever it may be located.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.210.71