will be used by a subsequent part of the query to produce the final result. This is called a
query continuation
clause. It has the following general form:
is the name of the range variable that iterates over the temporary result and is
—it continues the query. In essence, a query
continuation embodies the concept of building a new query that queries the results of the
preceding query.
. The following program reworks the
domain name. In this case, the initial results are queried by a range variable called
ws
. This
// Use into with group.
564
P a r t I :
T h e C # L a n g u a g e
// Create a query that groups websites by top-level domain name,
// but select only those groups that have more than two members.
// Here, ws is the range variable over the set of groups
// returned when the first half of the query is executed.
var webAddrs = from addr in websites
where addr.LastIndexOf(".") != -1
group addr by addr.Substring(addr.LastIndexOf("."))
into ws
where ws.Count() > 2
select ws;
// Execute the query and display the results.
Console.WriteLine("Top-level domains with more than 2 members.\n");
foreach(var sites in webAddrs) {
Console.WriteLine("Contents of " + sites.Key + " domain:");
foreach(var site in sites)
Console.WriteLine(" " + site);
Console.WriteLine();
}
}
}
The following output is produced:
Top-level domains with more than 2 members.
Contents of .net domain:
hsNameB.net
hsNameC.net
hsNameH.net
As the output shows, only the
.net
group is returned because it is the only group that has
more than two elements.
In the program, pay special attention to this sequence of clauses in the query:
group addr by addr.Substring(addr.LastIndexOf(".", addr.Length))
into ws
where ws.Count() > 2
select ws;
First, the results of the
group
clause are stored (creating a temporary result) and a new query
begins that operates on the stored results. The range variable of the new query is
ws
. At this
point,
ws
will range over each group returned by the first query. (It ranges over groups
because the first query results in a sequence of groups.) Next, the
where
clause filters the
query so the final result contains only those groups that contain more than two members. This
determination is made by calling
Count( )
, which is an
extension method
that is implemented
for all
IEnumerable
objects. It returns the number of elements in a sequence. (You’ll learn
more about extension methods later in this chapter.) The resulting sequence of groups is
returned by the
select
clause.
www.freepdf-books.com