Editorials

Learning Linq From SQL

One of the things I like about working in Dot Net is the Linq libraries. Having worked in SQL for so many years I have found my brain twisted to think in sets. There are so many things we do with sets, yet the sets we have available are not always in a relational database. Linq fills that gap quite nicely. While we can use traditional iteration patters such as a foreach or for loops, the Linq syntax is more friendly and represents the work I am trying to accomplish more clearly to persons familiar with the syntax.

One of the things I find useful to do using Linq is to compare two sets. So, for this comparison, let’s use two sets of names as an example. It doesn’t matter what the strings are, just that we have two sets, and we want to know how the data from one may be compare to the other.

A common requirement is to compare two sets, and find if set A has any record also in set B. There are a few ways you could put that together. In SQL Server I would use the EXISTS operation base on joining the two sets. The EXISTS operation ends query execution when the first joined record is located in both sets, returning a true value, which answers my question.

IF EXISTS

(

SELECT 1

FROM SETA

JOIN SETB ON SETA.Name = SETB.Name

)

PRINT 'FOUND'

ELSE

PRINT 'NOT FOUND'

You can do a similar kind of query using a Linq join. There are a number of different syntax methods for doing a join in Linq. I’ll use my favorite. In this case I am using two sets, seta and setb which are List collections.

var result = seta

.Join(setb, a=> a.name, b=> b.name, (a, b) a.name)

.FirstOrDefault();

if (result!=null) Console.WriteLine("Found");

else Console.WriteLine(“Not Found”);

The two different implementations work essentially the same. So, when I come to writing Linq queries, I find knowing some of the ways I would solve the question using SQL syntax can lead me to a similar implementation using Linq.

There are other ways to answer the same question in both SQL and Linq. Perhaps you’d like to share your favorite in our comments?

Cheers,

Ben