The Query Methods
The query syntax described by the preceding sections is the way you will probably write
most queries in C#. It is convenient, powerful, and compact. It is, however, not the only way
to write a query. The other way is to use the
query methods.
These methods can be called on
any enumerable object, such as an array.
The Basic Query Methods
The query methods are defined by
System.Linq.Enumerable
and are implemented as
extension methods
that extend the functionality of
IEnumerable
. (Query methods are
also defined by
System.Linq.Queryable
, which extends the functionality of
IQueryable
,
but this interface is not used in this chapter.) An extension method adds functionality to
another class, but without the use of inheritance. Support for extension methods was added
by C# 3.0, and we will look more closely at them later in this chapter. For now, it is sufficient
to understand that query methods can be called only on an object that implements
IEnumerable
.
The
Enumerable
class provides many query methods, but at the core are those that
correspond to the query keywords described earlier. These methods are shown here, along
with the keywords to which they relate. Understand that these methods have overloaded
forms and only their simplest form is shown. However, this is also the form that you will
often use.
Query Keyword
Equivalent Query Method
select
Select(
arg
)
where
Where(
arg
)
orderby
OrderBy(
arg
) or OrderByDescending(
arg
)
join
Join(
seq2
,
key1
,
key2
,
result
)
group
GroupBy(
arg
)
Except for
Join( )
, the other methods take one argument,
arg,
which is an object of type
FuncTResult>
, as a parameter. This is a delegate type defined by LINQ. It is declared
like this:
delegate TResult Func(T
arg
)
Here,
TResult
specifies the result of the delegate and
T
specifies the parameter type. In the
query methods,
arg
determines what action the query method takes. For example, in the
case of
Where( )
,
arg
determines how the query filters the data. Each of these query methods
returns an enumerable object. Thus, the result of one can be used to execute a call on
another, allowing the methods to be chained together.
The
Join( )
method takes four arguments. The first is a reference to the second sequence
to be joined. The first sequence is the one on which
Join( )
is called. The key selector for the
first sequence is passed via
key1,
and the key selector for the second sequence is passed via
www.freepdf-books.com
Do'stlaringiz bilan baham: |