无法将Statement Lambda放在LINQ查询中

Joh*_*n K 2 .net c# linq datacontext lambda

我正在尝试将一些内联工作作为语句Lambda注入到LINQ查询中select,如此...

// NOTE: mcontext.Gettype() == System.Data.Linq.DataContext

// Okay - compiles, nothing unusual
var qPeople1 = from ME.tblPeople person in mcontext.tblPeoples
              select person;

// ERROR - see below compile Error - Can I retrofit this thing?
var qPeople2 = from ME.tblPeople person in mcontext.tblPeoples
               select (() => { 
                   return person; 
               })();
Run Code Online (Sandbox Code Playgroud)

错误:

错误2方法名称预期file.cs 166 27 MigrationCore

...但是我也同样很高兴看到Expression Lambda首先内联工作.

注意:我知道代码示例是多余的,但我正在寻找基本概念.如果它可行,我将扩展它.

Zoo*_*oba 5

查询语法需要一个方法引用 - 它不接受lambda,在你的第二个例子中你给它一个ME.tblPeople实例.

但是,如果使用扩展方法语法,则可以轻松实现此目的:

int i = 0;
var qPeople3 = (from ME.tblPeople person in mcontext.tblPeoples
                select person).Select(person => { i += 1; return person; });
Run Code Online (Sandbox Code Playgroud)

(我已经添加了递增整数作为示例,但请注意,在您枚举之前它实际上不会从零变化qPeople3.)

附录

这仅适用于LINQ to Objects.要在LINQ to SQL查询中使用它,在AsEnumerable()调用之前需要Select()调用.

笔记

你实际上并不需要from-in-select这个例子的构造,下面的片段是(AFAICT)相同的,但我把它留在上面与前面的例子相似,并说明它是有效的.第二个片段将两个语句分成不同的行,也有相同的结果.

int i = 0;
var qPeople4 = mcontext.tblPeoples.Select<ME.tblPeople,ME.tblPeople>(person => { i += 1; return person; });
Run Code Online (Sandbox Code Playgroud)
int i = 0;
var qPeople1 = from ME.tblPeople person in mcontext.tblPeoples
               select person;
var qPeople5 = qPeople1.Select(person => { i += 1; return person; });
Run Code Online (Sandbox Code Playgroud)