Converting F# Quotations into LINQ Expressions

大城市里の小女人 提交于 2019-12-01 03:34:13

I'm not sure if this is directly supported by the LINQ modules available in the F# PowerPack. However, you can implement your own post-processing of the LINQ expression produced by F# libraries to turn it into a C# lambda function of the usual form:

The following function takes a LINQ expression which is constructed as multiple nested LambdaExpression expressions of a single parameter (that is, the structure produced by F# translator) and returns a list of parameters and body of the inner-most expression:

let rec translateExpr (linq:Expression) = 
  match linq with
  | :? MethodCallExpression as mc ->
      let le = mc.Arguments.[0] :?> LambdaExpression
      let args, body = translateExpr le.Body
      le.Parameters.[0] :: args, body
  | _ -> [], linq

Now you can use it to get an ordinary Func delegate out of type such as int -> int -> int -> int like this:

let linq = (<@@ fun a b c -> (a + b) * c @@>).ToLinqExpression()
let args, body = translateExpr liq
let f = Expression.Lambda<Func<int, int, int, int>>
          (body, args |> Array.ofSeq)
f.Compile().Invoke(10, 11, 2)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!