Wednesday, February 29, 2012

Linq to Objects and Linq To SQL : Part 1

Hack the Gibson

Linq or Language Integrated Query became available for the .Net Framework in 3.0.  Unlike the naming convention suggests between .Net 2.0 and .Net 4.0 frameworks, there were no true distributed builds for the framework.  What this means is that Microsoft took the approach that adding to the framework rather than opening it up and rewriting the framework from anew, they simply left the framework pieces that existed in place and added new portions as needed.  This is small but significant as Linq was released with .Net 3.0.  It originally came as an add-on instead of being completely integrated into the framework.
What the hell are you talking about, you might ask.
Well, until .Net 4.0 Framework was released, Linq was not truly integrated into the framework.  Thus, you had access to Linq to SQL but had to wait until .Net 4.0 to be released to gain access to Linq to Objects (unless you applied the service packs).
This being considered, Linq to SQL has been available since November 2006.  However, you could not truly use Linq to Objects until April 2010.  The release for .Net 4.5 framework is slated for late 2012 or early 2013 (you can never tell with Microsoft).

The beauty behind Linq is in its simplicity.  In .Net 4.0 Framework, the Linq engine grew larger by the addition of PLinq or Parallel Language Integrated Query.  PLinq defines the IParallelEnumerable<T> interface, meaning that if the source collection implements the interface, Linq can execute the query against it in a multi-thread style fashion (giving return result sets faster).

There are several Namespaces that you need to be aware of before we can start on our adventure.  They are listed below.

  1. System.Linq – This gives us access to Enumerable and Queryable classes inside link and is primarily used for Linq to Objects.
  2. System.Data.Linq – This namespace is used for relational databases (for instance SQL)
  3. System.XML.Linq – If you aren’t catching onto the namespace naming conventions yet, this namespace will allow you to query XML using Linq to XML.

In order for us to query against objects, we will use System.Linq.  So, to get a basic idea of how this works lets create the default .Net 4.0 ASP.NET website.

On the default page, let’s add some controls so that we can see our application working.
We need to add a Label so that we can display our query result, also we’ll need a button to trigger an event for our query:

<asp:Label ID="lblNamesList" runat="server" />

    <br />

    <asp:Button ID="btnLinqToObject" runat="server" Text="Linq To Object" />

If we press F5 and enter into debug mode, we’ll end up seeing the button but no text for our Label.  Let’s change that.  Next we’ll need to move into the code behind and we’ll need to tap the resources of System.Linq so lets go ahead and import it:

Imports System.Linq

Imports System.Text

Notice I also imported System.Text.  This is to support the StringBuilder I will need in order to populate the Label.  Let’s go ahead and setup our trigger.  Go ahead and select our button in the objects dropdown:


Now let’s go ahead and choose the click event:


This gives us the following result in our code behind:


So now we have our trigger for our click event of the button.  Now we get into the nitty gritty of Linq.  Let me show you how difficult it is to query Linq.  We need to setup a string array so that we can populate it with some values to query against.  In this case, I populated it with first names of people in my office:


You just completed the hardest part of Linq to Objects (getting an object that has been populated with values).  From there, we need to create our query:


Ok, so what are we doing here? I know it looks scary, but honestly when you understand what is going on, it not only makes perfect sense – it becomes kindergarten easy.

Obviously, we are dimensioning an object called namesWithLessThanFiveCharacters.  Notice the IEnumerable(Of String) object type.  The I in front of Enumerable is a naming convention that lets us know that we will be using an Interface.  Interface are much like abstract classes however they aren’t as restrictive.  They are best described as contracts between two objects.  The IEnumerable is an interface that is implemented for collections.  In this case, of type String – Thus, we have (Of String). 
So lets think about this a little bit, why would we need to implement the IEnumerable interface?  Well you aren’t going to query a single string.  So the idea behind it is that we are going query a collection of strings (thus our string array).  On the right hand side of the equals sign, we have the from name in employees where name.length < 5.  Lets break this up:

From name In employees is the Linq equivalent of saying 
For Each name As String In employees


So it just iterates through our employees array and finds the values that renders boolean true to our Where clause of name.Length < 5 (Where the length of name is greater than 5).  Due to the fact that Linq is a query language we know that we are going to query an object and then place the result set into our implemented Interface.  Now for the helper logic to facilitate populating our Label:


So our entire code sample looks like:

Imports System.Linq

Imports System.Text

Partial Class _Default

    Inherits System.Web.UI.Page


    Protected Sub btnLinqToObject_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLinqToObject.Click

    Dim employees() As String = {"Chad", "Kevin", "Jay", "Sean", "Paul", "David", "Danny"}


    Dim namesWithLessThanFiveCharacters As IEnumerable(Of String) = From name In employees Where name.Length < 5


    Dim namesList As New StringBuilder

    Dim comma As String = ""

    For Each name In namesWithLessThanFiveCharacters


        comma = ", "



    lblNamesList.Text = namesList.ToString()

End Sub




Here we are just building a StringBuilder.  Of course, we need to comma separate the values and then we are putting a .ToString() representation of the value into the Text property of our Label.  Thus, we end up with:


In the next article, we are going to look at Linq to SQL.

Happy .Netting…Saleh

Hack the Gibson

No comments:

Post a Comment