VB9 – LINQ and Extension Methods in Action

Here is the scenario, I have collection of books and I want to get a book with a specific ISBN.  In the old ways, you will probably have to create a custom collection and inherit a generic collection of books, then add a method to get by ISBN.

Thanks to LINQ and extension methods, you can do all this with under 3 lines of code.

First the book class looks like this:

Public Class book
    Public isbn As String
    Public Title As String
    Public Author As String
End
Class

Using an extension method called GetByISBN on a generic list of books, I write a LINQ query to select the book by ISBN from the collection:

 <Extension()> _
    Public Function GetByISBN(ByVal books As List(Of book), _
                              ByVal isbn As String) As book
        Dim query = From aBook In books _
                    Where aBook.isbn = isbn _
                    Select aBook
        Return query(0)
    End Function

Now, I can create a collection of books and get the book like this:

    Sub foo()
        Dim library As New List(Of book)
        Dim book = library.GetByISBN("0-672-32891-7")
    End Sub

You can see from the Intellisense that it is an extension method:

image

You can also see below that I didn’t have to explicitly declare book’s type but it was inferred

image

Microsoft, good job.

Advertisements

0 thoughts on “VB9 – LINQ and Extension Methods in Action

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s