CHAPTER 12 LINQ TO OBJECTS
The Role of Immediate Execution
When you need to evaluate a LINQ expression from outside the confines of foreach logic, you are able to
call any number of extension methods defined by the Enumerable type as ToArray(),
ToDictionary(), and ToList(). These methods will cause a LINQ query to execute at
the exact moment you call them, to obtain a snapshot of the data. After you have done so, the snapshot
of data may be independently manipulated:
static void ImmediateExecution()
{
int[] numbers = { 10, 20, 30, 40, 1, 2, 3, 8 };
// Get data RIGHT NOW as int[].
int[] subsetAsIntArray =
(from i in numbers where i < 10 select i).ToArray();
}
// Get data RIGHT NOW as List.
List subsetAsListOfInts =
(from i in numbers where i < 10 select i).ToList();
Notice that the entire LINQ expression is wrapped within parentheses to cast it into the correct
underlying type (whatever that might be) in order to call the extension methods of Enumerable.
Also recall from Chapter 9 that when the C# compiler can unambiguously determine the type
parameter of a generic, you are not required to specify the type parameter. Thus, you could also call
ToArray() (or ToList() for that matter) as follows:
int[] subsetAsIntArray =
(from i in numbers where i < 10 select i).ToArray();
The usefulness of immediate execution is very obvious when you need to return the results of a LINQ
query to an external caller. And, as luck would have it, this happens to be the next topic of this chapter.
Source Code The LinqOverArray project can be found under the Chapter 12 subdirectory.
Returning the Result of a LINQ Query
It is possible to define a field within a class (or structure) whose value is the result of a LINQ query. To do
so, however, you cannot make use of implicit typing (as the var keyword cannot be used for fields) and
the target of the LINQ query cannot be instance-level data; therefore, it must be static. Given these
limitations, you will seldom need to author code like the following:
class LINQBasedFieldsAreClunky
{
private static string[] currentVideoGames = {"Morrowind", "Uncharted 2",
"Fallout 3", "Daxter", "System Shock 2"};
// Can't use implicit typing here! Must know type of subset!
private IEnumerable subset = from g in currentVideoGames
452