A A
RSS

VB9 – LINQ and Extension Methods in Action

Fri, Nov 30, 2007

Programming

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.

Tags: , ,

  • techproject
    Microsoft, good job.
blog comments powered by Disqus
Advertise Here
The Most Intelligent Add-In To Visual Studio Happy fan of

What I'm Doing...

Yonkly Open Source

Sign up for my newsletter




* = required field

powered by MailChimp!

megree Widget

Apparently, I am connected to Obama. Check this out...
My path to Obama

Cyber Identity