Datasheet
Klein c01.tex V3 - 12/13/2007 1:48pm Page 11
Chapter 1: Project LINQ
and so on). The operators form a LINQ query pattern that operates on a sequence (an object that imple-
ments the
IEnumerable
<
T
> or
IQueryable
<
T
> interface).
There are two sets of standard query operators—one operates on objects of the
IEnumerable
<
T
> type
and the other operates on objects of the
IQueryable
<
T
> type. The operators are made up of methods
that are static members of the
Enumerable
and
Queryable
classes, allowing them to be called using static
method syntax of instance method syntax. You will learn all about this in Chapter 4.
The standard query operators can be categorized by their operation ‘‘type.’’ For example, there are
aggregate, projection, ordering, and grouping operators, among others. Take a look again at one of the
examples used earlier in the chapter (repeated here for your convenience):
private void ShowLINQ()
{
string [] firstnames = { "Scott", "Steve", "Ken", "Joe", "John",
"Alex", "Chuck", "Sarah"};
IEnumerable
<
string
>
val = from fn in firstnames
where fn.StartsWith("S")
select fn;
foreach (string name in val)
{
Console.WriteLine(name);
}
}
The actual LINQ query is the middle part:
val = from fn in firstnames
where fn.StartsWith("S")
select fn;
In this example, several query operators are utilized from different operation types. The
select
query
operator falls into the category of projection operators, and performs a projection over a sequence, an
object that implements the
IEnumerable
<
T
> for a given type. In this case, the
select
operator enumer-
ates the source sequence of first names.
select fn;
The
where
query operator is of the restriction operator type—in fact, it is the only operator of that type.
Just like T-SQL, the LINQ
where
operator filters a sequence. In the preceding example, it filters the
sequence by limiting the results returned to only those whose name begins with the letter S.
where fn.StartsWith("S")
If you are trying this example out yourself, create a new Windows Forms project and place a list box on
the form. In the
Load
event of the form, place the following code:
string [] firstnames = { "Scott", "Steve", "Ken", "Joe", "John",
"Alex", "Chuck", "Sarah"};
11