Skip to main content

A C# LINQ query is basically a set of instructions for how to retrieve and organize data. To execute the query requires a call to its GetEnumerator method. This call is made when you use a foreach loop to iterate over the elements. To evaluate a query and store its results without executing a foreach loop, just call one of the following methods on the query variable: ToList, ToArray, ToDictionary or ToLookup.

// ----------------------------------------------------------------------------
// Store the Results of a Query in Memory
// https://msdn.microsoft.com/en-us/library/bb513810.aspx
//
// A query is basically a set of instructions for how to retrieve and organize
// data. To execute the query requires a call to its GetEnumerator method. This
// call is made when you use a foreach loop to iterate over the elements. To
// evaluate a query and store its results without executing a foreach loop, just
// call one of the following methods on the query variable:
//
// - ToList<TSource>
// - ToArray<TSource>
// - ToDictionary<TSource, TKey, TElement>
// - ToLookup<TSource, TKey, TElement>
//
// We recommend that when you store the query results, you assign the returned
// collection object to a new variable as shown in the following example:
// ----------------------------------------------------------------------------
using System.Linq;
using System;
using System.Collections.Generic;

class StoreQueryResults
{
    static List<int> numbers = new List<int>() { 1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

    static void Main()
    {
        IEnumerable<int> queryFactorsOfFour =
            from num in numbers
            where num % 4 == 0
            select num;

        // Store the results in a new variable
        // without executing a foreach loop.
        List<int> factorsofFourList = queryFactorsOfFour.ToList();

        // Iterate the list just to prove it holds data.
        foreach (int n in factorsofFourList)
        {
            Console.WriteLine(n);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key");
        Console.ReadKey();
    }
}

// --------------------
// Output
// 4
// 8
// 12
// 16
// 20