现在的位置: 首页 > 综合 > 正文

LINQ在内存中存储查询结果

2013年08月02日 ⁄ 综合 ⁄ 共 722字 ⁄ 字号 评论关闭

查询基本上是一组有关如何检索和组织数据的指令。若要执行查询,需要调用它的 GetEnumerator 方法。当您使用 foreach 循环来循环访问元素时,将执行此调用。若要在执行 foreach 循环之前或之后的任何时间存储结果,只需对查询变量调用下列方法之一:

  • ToList<(Of <(TSource>)>)

  • ToArray<(Of <(TSource>)>)

  • ToDictionary

  • ToLookup

建议在存储查询结果时,将返回的集合对象分配给一个新变量,如下面的示例所示:

 

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

结果为:

tmp52

抱歉!评论已关闭.