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 ...

Get Professional Visual Studio® 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.