HomeBlogsgstevens's blogTechnote: LINQ to the Rescue

Technote: LINQ to the Rescue

This technote briefly explores one of Microsoft's best ideas over the last several years. Specifically, we're going to talk about LINQ, or Language-Integrated Query.

LINQ is an evolving method of using constructs in a language to perform queries on data. To understand what is meant by this, we need to revisit the traditional method of using SQL to access data. Let's assume we have a database table called Employees. To retrieve all elements from Employees with a first name of "Elizabeth", we might write something like the following in C#:

SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
SqlCommand cmd = null;
SqlDataReader reader = null;
cmd = new SqlCommand("SELECT * FROM Employees WHERE fname='Elizabeth'", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
reader = cmd.ExecuteReader();
conn.Close();

The interesting thing to note in the above is that we have to enter a string as part of our code. That is, the "SELECT * FROM Employees WHERE fname='Elizabeth'" SQL query cannot be checked at compile time. It is merely a string that gets sent to the DBMS for interpretation. Wouldn't it be better to liberate this query from being a string and have it become a first-class citizen in the code?

That is where LINQ steps in. Specifically, the above might be reworked as follows:

List results = (from emp in Employees where emp.fname="Elizabeth" select emp).ToList();

This code is all in C# and can be checked at compile time. In addition, if you are using Visual Studio and run your application in the debugger, you can check the SQL the gets generated from this command by hovering over the code and opening up the SQL Server Query Visualizer.

The above example demonstrates what is called LINQ to SQL. The LINQ system is much more powerful than just this common form for accessing data residing in SQL Server databases. You can also use the same basic constructs to access XML via LINQ to XML, or data residing in databases other than SQL Server via LINQ to DataSets. Indeed, there are many LINQ providers:

This list is only a modest survey the providers now available to .Net developers. And, the list is expanding at a steady pace.

The above is reason alone to explore LINQ on your own. But, as added incentive, I've saved the best for last. Specifically, LINQ to Objects.

LINQ to Objects
Suppose you have a software need to work with triangles represented by three vectors. Let's say you smartly created a nice little class to represent triangles:

Class Triangle
{
vector pointA;
vector pointB;
vector pointC;

double area { get { /* figure out the area of the triangle here */ } }
vector shortestEdge { get { /* calculate the triangle's shortest edge */ } }
...
}

Let's also say you have created hundreds of these objects and placed them in a convenient list called triangles:

List triangles = new List();
for (awhile)
{
/* make a new triangle called t */
triangles.Add(t);
}

You can now operate on the list called "triangles" using LINQ! For example, suppose you want the one with the largest area:

triangle bigArea = (from t in triangles orderby area descending select t).FirstOrDefault();

Dyed in the wool coders will look at this and say 'I could easily do that in a simple for-loop, so why learn this LINQ thing?' True, it is fairly easy to do the above in straight code. But, when the object you are searching for is based on multiple criteria, the value of LINQ to Objects starts to truly emerge. Let's say we want to find the largest area where the shortest edge is no greater than, say, 144. For that, we again could write code, but augmenting the above is much, much simpler:

triangle bigAreaShortEdge = (from t in triangles where t.shortestEdge <= 144 orderby area descending select t).FirstOrDefault();

As can be seen, if you need to maintain and perhaps augment this system from time to time, this construct is vastly simpler to manage than having multiple nested loops that take time to write and debug. Further, if a new attribute is needed in order to select a triangle, you can easily add a new property to the triangle class and use it immediately in your LINQ to Objects code.

I hope this information and the examples above inspire you to explore LINQ. If you already are using LINQ, I hope this gives you incentive to find new opportunities to use the powerful tool in new and useful ways.

Are you using LINQ in an innovative way? If so, please leave a comment. I'd appreciate seeing how others use LINQ to solve coding challenges.

Other Resources


Comments


Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.