可能重复:
在c#中组合两个lamba表达式
我有两个以下表达式:
Expression<Func<string, bool>> expr1 = s => s.Length == 5;
Expression<Func<string, bool>> expr2 = s => s == "someString";
Run Code Online (Sandbox Code Playgroud)
现在我需要将它们与OR结合起来.像这样的东西:
Expression.Or(expr1, expr2)
Run Code Online (Sandbox Code Playgroud)
有没有办法使这类似于上面的代码方式:
expr1 || expr2
Run Code Online (Sandbox Code Playgroud)
我理解在这个例子中我可以将它组合在一起:
Expression<Func<string, bool>> expr = s => s.Length == 5 || s == "someString"
Run Code Online (Sandbox Code Playgroud)
但我不能在我的真实代码中这样做,因为我将expr1和expr2作为方法的参数.
给定这样的类结构:
public class GrandParent
{
public Parent Parent { get; set;}
}
public class Parent
{
public Child Child { get; set;}
}
public class Child
{
public string Name { get; set;}
}
Run Code Online (Sandbox Code Playgroud)
和以下方法签名:
Expression<Func<TOuter, TInner>> Combine (Expression<Func<TOuter, TMiddle>>> first, Expression<Func<TMiddle, TInner>> second);
Run Code Online (Sandbox Code Playgroud)
我如何实现所述方法,以便我可以像这样调用它:
Expression<Func<GrandParent, Parent>>> myFirst = gp => gp.Parent;
Expression<Func<Parent, string>> mySecond = p => p.Child.Name;
Expression<Func<GrandParent, string>> output = Combine(myFirst, mySecond);
Run Code Online (Sandbox Code Playgroud)
这样输出结果如下:
gp => gp.Parent.Child.Name
Run Code Online (Sandbox Code Playgroud)
这可能吗?
每个Func的内容只会是一个MemberAccess.我宁愿不最终output成为嵌套函数调用.
谢谢
我正在尝试基于Specification对象动态构建表达式.
我创建了一个ExpressionHelper类,它有一个私有表达式,如下所示:
private Expression<Func<T, bool>> expression;
public ExpressionHelper()
{
expression = (Expression<Func<T, bool>>)(a => true);
}
Run Code Online (Sandbox Code Playgroud)
然后一些简单的方法如下:
public void And(Expression<Func<T,bool>> exp);
Run Code Online (Sandbox Code Playgroud)
我正在和And方法的身体挣扎.我基本上想要撕掉身体exp,用那些参数替换所有参数expression然后将它附加到expression身体的末端和AndAlso.
我这样做了:
var newBody = Expression.And(expression.Body,exp.Body);
expression = expression.Update(newBody, expression.Parameters);
Run Code Online (Sandbox Code Playgroud)
但最终我的表达看起来像这样:
{ a => e.IsActive && e.IsManaged }
Run Code Online (Sandbox Code Playgroud)
有更简单的方法吗?或者我怎样才能撕掉那些e并用一个替换它们?
我的代码收到此错误消息:“从范围''引用的'System.Int32'类型的变量'assignVal',但未定义”
我退房了
但不幸的是,我的示例似乎更简单,但由于某种原因仍然无法正常工作。
这是我的代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection.Emit;
using System.Threading.Tasks;
using static System.Linq.Expressions.Expression;
namespace ExpressionTests
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine(GetSyncAddExpression()(5) == 6);
Console.ReadKey();
Console.WriteLine(await GetTaskAddExpression()(5) == 6);
Console.ReadKey();
}
private static Func<int, Task<int>> GetTaskAddExpression()
{
var fromResultMethod = typeof(Task).GetMethod(nameof(Task.FromResult)).MakeGenericMethod(typeof(int));
var inParam = Parameter(typeof(int), "p1");
var assignmentValue = Variable(typeof(int), "assignVal");
var retVal = Variable(typeof(Task<int>));
var lambda …Run Code Online (Sandbox Code Playgroud)