共用方式為


HOW TO:將查詢的結果儲存在記憶體中 (C# 程式設計手冊)

更新:2007 年 11 月

查詢基本上是如何擷取及組織資料的一組指示。若要執行查詢,需要呼叫其 GetEnumerator 方法。在您使用 foreach 迴圈反覆查看項目時會進行此呼叫。若要在執行 foreach 迴圈之前或之後的任何時間儲存結果,只要在查詢變數上呼叫下列其中一個方法即可:

建議當您儲存查詢結果時,將傳回的集合物件指派給新變數,如下列範例所示:

範例

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

編譯程式碼

  • 建立以 .NET Framework 3.5 版為目標的 Visual Studio 專案。根據預設,專案有 System.Core.dll 的參考,以及 System.Linq 命名空間的 using 指示詞。

  • 將程式碼複製至您的專案中。

  • 按 F5 編譯和執行程式。

  • 按任何鍵離開主控台視窗。

請參閱

概念

LINQ 查詢運算式 (C# 程式設計手冊)