您的位置:首页 > 其它

Linq查询的延迟执行

2011-04-05 21:04 429 查看
  Linq查询表达式在我们迭代内容前,不会真正进行运算,这叫做延迟执行。这种方式的好处是可以为相同的容器多次应用相同的Linq查询,而始终获得最新的结果。

  示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestVar
{
class Program
{
//Linq查询的延迟执行示例
static void Main(string[] args)
{
int[] intAry = new int[] { 1, 2, 3, 4, 5, 6 };

//为varSet定义查询条件
var varSet = from x in intAry
where x % 2 == 0
select x;

//输出查询结果
foreach (var v in varSet)
{
Console.Write(v.ToString() + " ");
}

Console.WriteLine();

//修改数组元素
intAry[0] = 8;

//输出查询结果
foreach (var v in varSet)
{
Console.Write(v.ToString() + " ");
}

Console.ReadKey();
}
}
}


  这段程序的输出为:



  可以看出,修改数组元素后,我们无需为varSet重新定义Linq查询就能使用迭代直接获取最新的结果。

  那如何让Linq查询立即执行呢?Enumerable定义了诸如ToArray<T>()、ToDictionary<TSource, TKey>()、ToList<T>()在内的许多扩展方法,它们允许我们以强类型容器来捕获Linq查询结果。然后,这个容器就不会再“连接”到Linq表达式了,可以独立操作,示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestVar
{
class Program
{
static void Main(string[] args)
{
int[] intAry = new int[] { 1, 2, 3, 4, 5, 6 };

//使用强类型立即获取查询结果
List<int> intList = (from x in intAry
where x % 2 == 0
select x).ToList();

//输出查询结果
foreach (int v in intList)
{
Console.Write(v.ToString() + " ");
}

Console.ReadKey();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: