Expression拼接
程序员文章站
2022-04-15 21:22:38
public static class ExpressionHelp { /// /// Lambda表达式拼接 /// /// ///
public static class expressionhelp { /// <summary> /// lambda表达式拼接 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="first"></param> /// <param name="second"></param> /// <param name="merge"></param> /// <returns></returns> public static expression<t> compose<t>(this expression<t> first, expression<t> second, func<expression, expression, expression> 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<t>(merge(first.body, secondbody), first.parameters); } /// <summary> /// and扩展 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="first"></param> /// <param name="second"></param> /// <returns></returns> public static expression<func<t1, t2, bool>> and<t1, t2>(this expression<func<t1, t2, bool>> first, expression<func<t1, t2, bool>> second) { return first.compose(second, expression.and); } public static expression<func<t, bool>> and<t>(this expression<func<t, bool>> first, expression<func<t, bool>> second) { return first.compose(second, expression.and); } /// <summary> /// or扩展 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="first"></param> /// <param name="second"></param> /// <returns></returns> public static expression<func<t1, t2, bool>> or<t1, t2>(this expression<func<t1, t2, bool>> first, expression<func<t1, t2, bool>> second) { return first.compose(second, expression.or); } public static expression<func<t, bool>> or<t>(this expression<func<t, bool>> first, expression<func<t, bool>> second) { return first.compose(second, expression.or); } }