Skip to content

Instantly share code, notes, and snippets.

@newdigate
Last active April 19, 2023 15:31
Show Gist options
  • Save newdigate/1792202bb2774fd55175 to your computer and use it in GitHub Desktop.
Save newdigate/1792202bb2774fd55175 to your computer and use it in GitHub Desktop.
Chaining on where clause using OR operator #linq
public IEnumerable<MyEntity> GetMyEntitys(IEnumerable<long> MyEntityIds)
{
IEnumerable<IEnumerable<long>> segmentedMyEntitys = MyEntityIds.ToArray().Split(100);
IQueryable<EF.MyEntity> x = from MyEntity in _dbContext.MyEntitys select MyEntity;
Expression<Func<EF.MyEntity,bool>> expression = null;
foreach (IEnumerable<long> segmentedMyEntityIds in segmentedMyEntitys)
{
Expression<Func<EF.MyEntity,bool>> y = p => segmentedMyEntityIds.Contains(p.MyEntityId);
if (expression == null) {
expression = y;
}
else
expression = expression.Or(y);
}
IQueryable<EF.MyEntity> z = x.Where( expression );
return z.Select(_MyEntityRowConverter.Convert);
}
public static class PredicateBuilder {
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> a, Expression<Func<T, bool>> b) {
ParameterExpression p = a.Parameters[0];
SubstExpressionVisitor visitor = new SubstExpressionVisitor();
visitor.subst[b.Parameters[0]] = p;
Expression body = Expression.AndAlso(a.Body, visitor.Visit(b.Body));
return Expression.Lambda<Func<T, bool>>(body, p);
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> a, Expression<Func<T, bool>> b) {
ParameterExpression p = a.Parameters[0];
SubstExpressionVisitor visitor = new SubstExpressionVisitor();
visitor.subst[b.Parameters[0]] = p;
Expression body = Expression.OrElse(a.Body, visitor.Visit(b.Body));
return Expression.Lambda<Func<T, bool>>(body, p);
}
}
internal class SubstExpressionVisitor : ExpressionVisitor {
public Dictionary<Expression, Expression> subst = new Dictionary<Expression, Expression>();
protected override Expression VisitParameter(ParameterExpression node) {
Expression newValue;
if (subst.TryGetValue(node, out newValue)) {
return newValue;
}
return node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment