Quantcast
Channel: Recent Gists from badsyntax
Viewing all articles
Browse latest Browse all 37

c# predicate builder, useful for constructing linq predicates

$
0
0
ExpressionWhereFinder.cs
internal class ExpressionWhereFinder : ExpressionVisitor
{
private readonly IList<MethodCallExpression> _whereExpressions = new List<MethodCallExpression>();
public IEnumerable<MethodCallExpression> GetWhere(Expression expression)
{
Visit(expression);
return _whereExpressions;
}
protected override Expression VisitMethodCall(MethodCallExpression expression)
{
if (expression.Method.Name == "Where")
{
_whereExpressions.Add(expression);
}
Visit(expression.Arguments[0]);
return expression;
}
}
PredicateBuilder.cs
namespace MyApp.Linq
{
using System;
using System.Linq;
using System.Linq.Expressions;
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>()
{
return f => true;
}
public static Expression<Func<T, bool>> False<T>()
{
return f => false;
}
public static Expression<Func<T, bool>> Or<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2
)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2
)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
}
}
}

Viewing all articles
Browse latest Browse all 37

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>