表达式<Func<T,bool>来自 F# func [英] Expression<Func<T, bool>> from a F# func

查看:15
本文介绍了表达式<Func<T,bool>来自 F# func的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 linq 中,.Where 需要一个 Expression> 谓词,我可以在 F# 中将其写为

in linq, .Where takes a Expression> predicate, which I can write in F# as

<@ fun item:'a -> condition @>    // Expr<'a -> bool>

我使用 FSharp.Powerpack 从引用中构建表达式,但它给我的是 MethodCallExpression.深入研究,powerpack 代码正确构建了 lambda,但将其包装在 Convert 调用中(为什么会这样?).我想知道将参数转换为方法调用(一个 lambda)是否最终会给我我需要的表达式.

I'm using FSharp.Powerpack to build the expression from a quotation, but what it gives me is a MethodCallExpression. Looking deep, the powerpack code builds the lambda correctly, but wraps it in a Convert call (why is that?). I wonder if casting the argument to the method call (a lambda) would finally give me the Expression> I need.

所以问题是为什么要调用 Convert,以及如何实际获得带有 Func 签名的 lambda.

So the question is why the Convert call, and how to actually get the lambda with the Func signature.

推荐答案

我一时想不起来我是在哪里找到这段代码的,但这是我用来转换 Expr<'a ->'b>Expression>.希望这能解决您的问题.

I can't remember off the top of my head where I found this bit of code, but this is what I use to convert an Expr<'a -> 'b> to Expression<Func<'a, 'b>>. Hopefully this will solve your problem.

open System
open System.Linq.Expressions
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Linq.QuotationEvaluation

let toLinq (expr : Expr<'a -> 'b>) =
  let linq = expr.ToLinqExpression()
  let call = linq :?> MethodCallExpression
  let lambda = call.Arguments.[0] :?> LambdaExpression
  Expression.Lambda<Func<'a, 'b>>(lambda.Body, lambda.Parameters) 

这篇关于表达式&lt;Func&lt;T,bool&gt;来自 F# func的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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