Do at compile time Linq-To-Objects statements also get translated into Expression Tree objects?

我的梦境 提交于 2019-12-12 01:52:20

问题


At compile time LINQ statements that operate on IQueryable<T> ( thus Linq-to-SQL and Linq-to-Entities statements ) get translated into an expression tree objects that present code as data.

a) Do LINQ statements that operate on IEnumerable<T> ( thus LINQ-to-Objects ) also get translated into expression trees?

b) If not, what happens with LINQ-to-Object statements at compile time? Does compiler simply translate them into appropriate method calls? For example, is the next Linq-to-Objects statement:

var results = collection.Select(item => item.id).Where(id => id > 10);

translated by compiler into something similar to the following:

var results = Enumerable.Where(
                  Enumerable.Select(collection, item => item.id),
                  id => id > 10
              );

thank you


回答1:


If you reflect the code, the IEnumerable extension methods actually contain the implementation for whatever you're trying to do. If you are wanting it build build an expression tree, simply chain the AsQueryable() extension method at the beginning so your query becomes:

var results = collection.AsQueryable().Select(item => item.id).Where(id => id > 10);


来源:https://stackoverflow.com/questions/8405423/do-at-compile-time-linq-to-objects-statements-also-get-translated-into-expressio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!