CHAPTER 12 LINQ TO OBJECTS
Item: Uncharted 2
Once Again, Without LINQ
To be sure, LINQ is never mandatory. If you so choose, you could have found the same result set by
forgoing LINQ altogether and making use of programming primitives such as if statements and for
loops. Here is a method that yields the same result as the QueryOverStrings() method, but in a much
more verbose manner:
static void QueryOverStringsLongHand()
{
// Assume we have an array of strings.
string[] currentVideoGames = {"Morrowind", "Uncharted 2",
"Fallout 3", "Daxter", "System Shock 2"};
string[] gamesWithSpaces = new string[5];
for (int i = 0; i < currentVideoGames.Length; i++)
{
if (currentVideoGames[i].Contains(" "))
gamesWithSpaces[i] = currentVideoGames[i];
}
// Now sort them.
Array.Sort(gamesWithSpaces);
}
// Print out the results.
foreach (string s in gamesWithSpaces)
{
if( s != null)
Console.WriteLine("Item: {0}", s);
}
Console.WriteLine();
While I am sure you can think of ways to tweak the previous method, the fact remains that LINQ
queries can be used to radically simplify the process of extracting new subsets of data from a source.
Rather than building nested loops, complex if/else logic, temporary data types, and so on, the C#
compiler will perform the dirty work on your behalf, once you create a fitting LINQ query.
Reflecting over a LINQ Result Set
Now, assume the Program class defines an additional helper function named ReflectOverQueryResults()
that will print out various details of the LINQ result set (note the parameter is a System.Object, to
account for multiple types of result sets):
static void ReflectOverQueryResults(object resultSet)
{
Console.WriteLine("***** Info about your query *****");
Console.WriteLine("resultSet is of type: {0}", resultSet.GetType().Name);
447