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:

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

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.