简体   繁体   English

如何使用F#lambda创建Linq表达式树?

[英]How do I create a Linq expression tree with an F# lambda?

Here's what can be done in C# - 这是C#可以做的 -

var two = 2;
System.Linq.Expressions.Expression<System.Func<int, int>> expr = x => x * two;
expr.Compile().Invoke(4); // returns 8

I wish to do the precise equivalent in F#. 我希望在F#中做到精确的等价物。 Here's what I tried, but did not compile - 这是我尝试过的,但没有编译 -

let two = 2
let expr = (fun x -> x * two) : System.Linq.Expressions.Expression<System.Func<int, int>>
expr.Compile().Invoke(4) // desired to return 8

Perhaps predictably, compilation fails on line 2 with the following error - 也许可以预见,编译在第2行失败,出现以下错误 -

"This function takes too many arguments, or is used in a context where a function is not expected."
let expr = (fun x -> x * two) : System.Linq.Expressions.Expression<System.Func<int, int>>
            ^^^^^^^^^^^^^^^^

I'm not sure why you want to avoid using F# quotations - under the cover, they are pretty much the same thing as C# expression trees and if you want to create an expression tree in F#, the compiler will be using quotations under the cover in any case... 我不确定为什么要避免使用F#引用 - 在封面下,它们与C#表达式树几乎相同,如果要在F#中创建表达式树,编译器将在封面下使用引号任何状况之下...

Anyway, you can do this without writing explicit <@ .. @> because the compiler can automatically quote a function when it is passed as an argument to a method. 无论如何,您可以在不编写显式<@ .. @>情况下执行此操作,因为编译器可以在将函数作为参数传递给方法时自动引用该函数。 So you can do: 所以你可以这样做:

type Expr = 
  static member Quote(e:Expression<System.Func<int, int>>) = e

let two = 2
let expr = Expr.Quote(fun x -> x * two) 
expr.Compile().Invoke(4) // desired to return 8

EDIT: However, this really compiles to an F# quotation wrapped in a call that converts it to C# expression tree. 编辑:但是,这实际上编译为包含在调用中的F#引用,该调用将其转换为C#表达式树。 So, in the end, you'll get the same thing as if you wrote: 所以,最后,你会得到和你写的一样:

open Microsoft.FSharp.Linq.RuntimeHelpers

let two = 2
let expr = 
  <@ System.Func<_, _>(fun x -> x * two) @>
  |> LeafExpressionConverter.QuotationToExpression 
  |> unbox<Expression<Func<int, int>>>
expr.Compile().Invoke(4) // desired to return 8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM