February 2009 - Posts

LINQ TO SQL Vs. Lambda Expressions

It is amazing how much you can achieve with Lambda expressions using a single line of code vs. several lines of Linq to Sql. Although, linq to sql is a better choice over traditional CRUD operations using sql and the like. Here's how... Create a new console application project in VS.Net 2008 and import the following name spaces in the module:
Imports System.Collections
Imports System.Linq

Let's declare an array of string as below:
Dim Provinces As String() = {"Ontario", "New Brunswick", "British Columbia", "PEI", "Quebec", "Manitoba", "Alberta", "Northern Territories"}

Using LINQ to SQL, iterate through the array list and write the result to a console as below:
Dim oProvince = From s In Provinces _
Where (s.StartsWith("N")) _
Select s

For Each province In oProvince


See the number of lines it took to display the provinces beginning with "N"!!!
With Lambda expressions, all of this can be achieved in a single line of code. See below:

For Each prov In Provinces.Where(Function(p) p.StartsWith("N"))


Lambda expressions are very powerful which take anonymous delegates to give you the desired result.
While I use LINQ TO SQL where necessary but don't miss a chance when it comes to Lambda expression usage.

Obi />