In the previous two chapters of this book, we used Service Factory to create the WCF service. In the data access layer, we used the raw ADO.NET SQL adapters to communicate with the Northwind database. In one of the following chapters, we will explain how to use LINQ to SQL in our data access layer.
But before using LINQ to SQL in our data access layer, we need to understand what it actually means by saying LINQ, or LINQ to SQL. Before understanding LINQ, we first need to understand some new C# features related to LINQ. In this chapter, we will first explore these new C# features related to LINQ, and then we will explore LINQ.
In this chapter, we will cover:
var
Language-Integrated Query (LINQ) is a set of features in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic.
Let us see an example first. Suppose there is a list of integers like this:
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 100 };
To find all the even numbers in this list, you might write some code like this:
List<int> list1 = new List<int>(); foreach (var num in list) { if (num % 2 == 0) list1.Add(num); }
Now with LINQ, you can select all of the even numbers from this list, and assign the query result to a variable,in just one sentence, like this:
var list2 = from number in list where number % 2 == 0 select number;
In this example, list2
and list1
are equivalent. list2
contains the same numbers as list1
does. As you can see, you don't write a foreach
loop. Instead, you write an SQL statement.
But what do from, where
and select
mean here? Where are they defined? How and when can I use them? Let us start the exploration now.