共用方式為


How to: Store the Results of a Query in Memory (C# Programming Guide)

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:

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:

Example

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();
    }
}

Compiling the Code

  • Create a Visual Studio project that targets the .NET Framework version 3.5. By default, the project has a reference to System.Core.dll and a using directive for the System.Linq namespace.

  • Copy the code into your project.

  • Press F5 to compile and run the program.

  • Press any key to exit the console window.

See Also

Concepts

LINQ Query Expressions (C# Programming Guide)