412
LESSON 37 LINQ to objects
The following code displays the even numbers between 0 and 99:
// Display the even numbers between 0 and 99.
private void Form1_Load(object sender, EventArgs e)
{
// 1. Create the data source.
int[] numbers = new int[100];
for (int i = 0; i < 100; i++)
{
numbers[i] = i;
}
// 2. Build a query to select data from the data source.
var evenQuery =
from int num in numbers
where (num % 2 == 0)
select num;
// 3. Execute the query and process the result.
foreach (int num in evenQuery)
{
Console.WriteLine(num.ToString());
}
}
The program starts by creating the data source: an array containing the numbers 0 through 99. In
this example the data source is quite simple, but in other programs it could be much more complex.
Instead of an array of numbers, it could be a list of
Customer objects, or an array of Order objects
that contain lists of
OrderItem objects.
Next the program builds a query to select the even numbers from the list. I explain queries in more
detail later, but the following list describes the key pieces of this query:
var
— This is the data type of whatever is returned by the query. In this example, the result
will be an
IEnumerable<int> but in general the results of LINQ queries can have some very
strange data types. Rather than trying to figure out what a query will return, most developers
use the implicit data type
var. The var keyword tells the C# compiler to figure out what the
data type is and use that so you don’t need to use a specific data type.
evenQuery
— This is the name the code is giving to the query. You can think of it as a vari-
able that represents the result that LINQ will later produce.
from int num in numbers
— This means the query will select data from the numbers
array. It will use the
int variable num to range over the values in the array. Because num
ranges over the values, it is called the query’s range variable. (If you omit the
int data type,
the compiler will implicitly figure out its data type.)
where (num % 2 == 0)
— This is the query’s where clause. It determines which items are
selected from the array. This example selects the even numbers where
num mod 2 is 0.
select num
— This tells the query to return whatever is in the range variable num for the
values that are selected. Often you will want to return the value of the range variable but you
could return something else such as
2 * num or a new object created with a constructor that
takes
num as a parameter.
596906c37.indd 412 4/7/10 12:34:59 PM