CHAPTER 12 LINQ TO OBJECTS
Note Although LINQ queries look similar to SQL queries, the syntax is not identical. In fact, many LINQ queries
seem to be the exact opposite format of a similar database query! If you attempt to map LINQ directly to SQL, you
will surely become frustrated. To keep your sanity, I’d recommend that you try your best to regard LINQ queries as
unique statements, which just “happen to look” similar to SQL.
When LINQ was first introduced to the .NET platform in version 3.5, the C# and VB languages were
each expanded with a large number of new programming constructs used to support the LINQ
technology set. Specifically, the C# language uses the following core LINQ-centric features:
•
Implicitly typed local variables
•
Object/collection initialization syntax
•
Lambda expressions
•
Extension methods
•
Anonymous types
These features have already been explored in detail within various chapters of the text. However, to
get the ball rolling, let’s quickly review each feature in turn, just to make sure we are all in the proper
mindset.
Implicit Typing of Local Variables
In Chapter 3, you learned about the var keyword of C#. This keyword allows you to define a local variable
without explicitly specifying the underlying data type. The variable, however, is strongly typed, as the
compiler will determine the correct data type based on the initial assignment. Recall the following code
example from Chapter 3:
static void DeclareImplicitVars()
{
// Implicitly typed local variables.
var myInt = 0;
var myBool = true;
var myString = "Time, marches on...";
// Print out the underlying type.
Console.WriteLine("myInt is a: {0}", myInt.GetType().Name);
Console.WriteLine("myBool is a: {0}", myBool.GetType().Name);
Console.WriteLine("myString is a: {0}", myString.GetType().Name);
}
This language feature is very helpful, and often mandatory, when using LINQ. As you will see during
this chapter, many LINQ queries will return a sequence of data types, which are not known until compile
time. Given that the underlying data type is not known until the application is compiled, you obviously
can’t declare a variable explicitly!
440