using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public static class LambdaExtension
{
public static Expression Property(this Expression expression, string propertyName)
{
return Expression.Property(expression, propertyName);
}
///
/// 组合AndAlso
///
///
///
///
public static Expression AndAlso(this Expression left, Expression right)
{
return Expression.AndAlso(left, right);
}
public static Expression Call(this Expression instance, string methodName, params Expression[] arguments)
{
return Expression.Call(instance, instance.Type.GetMethod(methodName) ?? throw new InvalidOperationException(), arguments);
}
public static Expression GreaterThan(this Expression left, Expression right)
{
return Expression.GreaterThan(left, right);
}
///
/// 转成Lambda表达式
///
///
///
///
///
public static Expression ToLambda(this Expression body, params ParameterExpression[] parameters)
{
return Expression.Lambda(body, parameters);
}
///
/// True
///
///
///
public static Expression> True() { return param => true; }
///
/// False
///
///
///
public static Expression> False() { return param => false; }
///
/// 组合And
///
///
public static Expression> And(this Expression> first, Expression> second)
{
return first.Compose(second, Expression.AndAlso);
}
///
/// 组合Or
///
///
public static Expression> Or(this Expression> first, Expression> second)
{
return first.Compose(second, Expression.OrElse);
}
///
/// Combines the first expression with the second using the specified merge function.
///
private static Expression Compose(this Expression first, Expression second, Func merge)
{
var map = first.Parameters
.Select((f, i) => new { f, s = second.Parameters[i] })
.ToDictionary(p => p.s, p => p.f);
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
return Expression.Lambda(merge(first.Body, secondBody), first.Parameters);
}
///
/// ParameterRebinder
///
private class ParameterRebinder : ExpressionVisitor
{
///
/// The ParameterExpression map
///
private readonly Dictionary _map;
///
/// Initializes a new instance of the class.
///
/// The map.
private ParameterRebinder(Dictionary map)
{
this._map = map ?? new Dictionary();
}
///
/// Replaces the parameters.
///
/// The map.
/// The exp.
/// Expression
public static Expression ReplaceParameters(Dictionary map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
///
/// Visits the parameter.
///
/// The p.
/// Expression
protected override Expression VisitParameter(ParameterExpression p)
{
if (_map.TryGetValue(p, out ParameterExpression replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}
}