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
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:
You can also see below that I didn’t have to explicitly declare book’s type but it was inferred
Microsoft, good job.