LINQ查询的执行流程 [英] Execution flow of a linq query

查看:64
本文介绍了LINQ查询的执行流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

case1

var numbers = new List<int>();
numbers.Add (1);
IEnumerable<int> query = numbers.Select (n => n * 10);    // Build query
numbers.Add (2);

//Use or execute query  

case2

var numbers = new List<int>() { 1, 2 };
numbers.Add(4);
List<int> query  = numbers
  .Select (n => n * 10) 
  .ToList();                      // Executes immediately into a List<int>
numbers.Add(3);
numbers.Clear();

//Use or execute query

为什么在第一种情况下查询同时包含1,2

Why in the first case query contains both 1,2

在第二种情况下,查询仅包含1,2,4而不包含3,是因为我们正在调用.ToList()方法.

In second case query contains only 1,2,4 but not 3,is it because we are calling .ToList() method.

推荐答案

这是因为直到您开始对结果集进行枚举(通过调用.ToArray()、. ToList()或简单地编写foreach才执行查询))

It's because the query is not executed until you start enumerating over the resultset (by either calling .ToArray(), .ToList(), or simply write a foreach)

IEnumerable<int> query = numbers.Select (n => n * 10);

不执行任何操作.这是LINQ的懒惰性质.

doesn't execute anything. It's the the lazy nature of LINQ.

这篇关于LINQ查询的执行流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆