using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace LeaRun.Util.Extension
{
///
/// Enables the efficient, dynamic composition of query predicates.
///
public static class LinqExtensions
{
public static Expression Property(this Expression expression, string propertyName)
{
return Expression.Property(expression, propertyName);
}
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), arguments);
}
public static Expression GreaterThan(this Expression left, Expression right)
{
return Expression.GreaterThan(left, right);
}
public static Expression ToLambda(this Expression body, params ParameterExpression[] parameters)
{
return Expression.Lambda(body, parameters);
}
public static Expression> True() { return param => true; }
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.
///
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
///
readonly Dictionary map;
///
/// Initializes a new instance of the class.
///
/// The map.
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)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}
}