Tuesday, January 20, 2009

LINQ Tips & Tricks - I Heart LINQ

Ok, I have to admit it; I heart LINQ... I have a man-crush on LINQ; if LINQ were a president it would be Baberaham LINQoln. Ok, that last one was pretty bad, but I have had that quote from Wayne's World floating around in my head for a while now and it had to come out sooner or later. :)

When I first heard about LINQ at a big Microsoft launch event I thought it was crap. The developer evangelist showed how you can generate inline SQL statements using LINQ and left it at that. My first thought was "great, a technology that takes us back to the stone ages of SQL development where developers don't put any thought into their database queries." How wrong I was; LINQ is awesome and can be a huge benefit to a single developer working with a local database, enterprise developers using stored procedures and developers not working with databases at all.

I purchased the most excellent "LINQ in Action" book by Fabrice Marguerie, Steve Eichert & Jim Wooley; which I have been reading through in my spare time. If you are looking for a good resource to learn LINQ beyond the web I highly recommend this book.

I have also been trying to use LINQ as much as possible in my development, as it is a huge time saver. Along the way I have learned a few tips & tricks for problems I needed to solve using LINQ which I will share with you below. I will follow up this post with other LINQ based posts including a couple of LINQ based ASP.NET controls that I am working on.


Remember to include a reference to LINQ in your project as well as your class before trying to use LINQ or you are going to have some problems.
C#: using System.Linq;
VB.NET: Imports System.Linq

Returning a Single Result from a LINQ Query

So lets say that you want to use a LINQ query to return a single result. How do you do that?

Here is an example:

string emailAddress = (from i in individuals
where i.MemberID.Equals(individual.MemberID)
select i.EmailAddress).Single();

Using a LINQ Like % Query

How do you write a query to search for a partial string match? Something like "WHERE s LIKE 'asdf%'

Here is an example:

string myPartialSearchString = "Smit";
var peoples = from i in individuals
where i.LastName.Contains(myPartialSearchString)
select i;

Handling NULL Parameters in a LINQ Queries

Lets say you have parameters(s) in your LINQ query where clause, how do you handle that?

Here is an example:

var peoples= from i in individuals
where (string.IsNullOrEmpty(lastName) i.LastName.Equals(lastName))
select i;

The C# ?? null coalescing operator (and using it with LINQ)

101 LINQ Examples

1 comment:

Unknown said...

Hey Aaron! Thanks for the mention of LINQ in Action and the kinds words, I'm very happy you've been enjoying it! :)