I'm creating some extension methods on IQueryable to make wildcard filtering easier. But I'm stumbling into a lot of exceptions when I try to filter a sub list. My example:
public class User {
public string FirstName { get; set; }
public string LastName { get; set; }
public IReadOnlyList<Address> Addresses { get; set; }
...
}
public class Address {
public string Street { get; set; }
...
}
My wildcard implementation speaks for itself, the method expects a list of values and supports StartsWith, EndsWith and Contains. I have a Filter method that looks like this:
public static IQueryable<T> Filter<T>(this IQueryable<T> query, Expression<Func<T, string>> property,
IList<string> values)
{
if (values == null || values.Count == 0)
return query;
Expression<Func<T, bool>> condition;
if (values.Count == 1)
condition = GetBooleanExpressionFromString(property, values.First()).Expand();
else
condition = GetBooleanExpressionFromStringList(property, values).Expand();
return query.Where(condition);
}
And the expressions builders look like:
private static Expression<Func<T, bool>> GetBooleanExpressionFromStringList<T>(
Expression<Func<T, string>> expression,
IList<string> values)
{
var predicate = PredicateBuilder.New<T>();
foreach (var value in values)
{
var parsedValue = value.Replace("*", string.Empty);
if (value.StartsWith("*") && value.EndsWith("*"))
predicate.Or(x => expression.Invoke(x).Contains(parsedValue));
else if (value.StartsWith("*"))
predicate.Or(x => expression.Invoke(x).EndsWith(parsedValue));
else if (value.EndsWith("*"))
predicate.Or(x => expression.Invoke(x).StartsWith(parsedValue));
else predicate.Or(x => expression.Invoke(x) == parsedValue);
}
return predicate;
}
public static Expression<Func<T, bool>> GetBooleanExpressionFromString<T>(
Expression<Func<T, string>> expression,
string value)
{
var parsedValue = value.Replace("*", string.Empty);
if (value.StartsWith("*") && value.EndsWith("*"))
return x => expression.Invoke(x).Contains(parsedValue);
if (value.StartsWith("*"))
return x => expression.Invoke(x).EndsWith(parsedValue);
if (value.EndsWith("*"))
return x => expression.Invoke(x).StartsWith(parsedValue);
return x => expression.Invoke(x) == parsedValue;
}
At the end I can use the Filter method like this:
var query = Session.Query<User>();
query = query.Filter(x => x.FirstName, new [] { "Foo*", "*Bar", "*test*" });
return query;
Now I want to make the same extension for the Street property of the Address list. In normal Linq it would compile to query.Where(x => x.Addresses.Any(y => y.Street.*wildcardstuff*)) and the Filter method would be called like query.Filter(x => x.Addresses, x => x.Street, values). But I'm keep getting NotSupported exceptions. The last thing I tried is this post from EF but its not that typed like i want it to be.
The last implementation I tried is this one:
public static IQueryable<T> FilterList<T, U>(this IQueryable<T> query, Expression<Func<T, IEnumerable<U>>> innerList, Expression<Func<U, string>> property,
IList<string> values)
{
if (values == null || values.Count == 0)
return query;
Expression<Func<U, bool>> condition;
if (values.Count == 1)
condition = GetBooleanExpressionFromString(property, values.First()).Expand();
else
condition = GetBooleanExpressionFromStringList(property, values).Expand();
return query.Where(i => innerList.Invoke(i).Any(j => condition.Invoke(j)));
}
but got this exception: System.NotSupportedException: Cannot parse expression 'x => x.Addresses' as it has an unsupported type. Only query sources (that is, expressions that implement IEnumerable) and query operators can be parsed.
I tried to make an extension on string with the wildcard logic but this throws also a NotSupported exception, anyone has an idea?
I would make it more universal. Which may simplify creating such extensions.
query = query.FilterByWildcard(x => x.FirstName, new [] { "Foo*", "*Bar", "*test*" });
And realization:
public static class QueryExtensions
{
public static IQueryable<T> FilterByWildcard<T>(this IQueryable<T> query, Expression<Func<T, string>> prop, IEnumerable<string> items)
{
return query.FilterBy(items, prop, s =>
{
var pattern = s.Trim('*');
if (s.StartsWith("*"))
if (s.EndsWith("*"))
return e => e.Contains(pattern);
else
return e => e.StartsWith(pattern);
else if (s.EndsWith("*"))
return e => e.EndsWith(pattern);
else
return e => e == s;
});
}
public static IQueryable<T> FilterBy<T, TProp, TItem>(this IQueryable<T> query,
IEnumerable<TItem> items,
Expression<Func<T, TProp>> prop,
Func<TItem, Expression<Func<TProp, bool>>> operationSelector, bool isOr = true)
{
var param = prop.Parameters[0];
Expression predicate = null;
foreach (var item in items)
{
var operation = operationSelector(item);
var body = ExpressionReplacer.GetBody(operation, prop.Body);
if (predicate == null)
{
predicate = body;
}
else
{
predicate = Expression.MakeBinary(isOr ? ExpressionType.OrElse : ExpressionType.AndAlso, predicate,
body);
}
}
if (predicate == null)
return query.Where(e => 1 == 2);
var lambda = Expression.Lambda<Func<T, bool>>(predicate, param);
return query.Where(lambda);
}
class ExpressionReplacer : ExpressionVisitor
{
readonly IDictionary<Expression, Expression> _replaceMap;
public ExpressionReplacer(IDictionary<Expression, Expression> replaceMap)
{
_replaceMap = replaceMap ?? throw new ArgumentNullException(nameof(replaceMap));
}
public override Expression Visit(Expression exp)
{
if (exp != null && _replaceMap.TryGetValue(exp, out var replacement))
return replacement;
return base.Visit(exp);
}
public static Expression Replace(Expression expr, Expression toReplace, Expression toExpr)
{
return new ExpressionReplacer(new Dictionary<Expression, Expression> {{toReplace, toExpr}}).Visit(expr);
}
public static Expression Replace(Expression expr, IDictionary<Expression, Expression> replaceMap)
{
return new ExpressionReplacer(replaceMap).Visit(expr);
}
public static Expression GetBody(LambdaExpression lambda, params Expression[] toReplace)
{
if (lambda.Parameters.Count != toReplace.Length)
throw new InvalidOperationException();
return new ExpressionReplacer(lambda.Parameters.Zip(toReplace)
.ToDictionary(e => (Expression)e.First, e => e.Second)).Visit(lambda.Body);
}
}
}
This answer is fixing my own method but Svyatoslav Danyliv's answer is more futureproof.
public static IQueryable<T> FilterList<T, U>(this IQueryable<T> query, Expression<Func<T, IEnumerable<U>>> innerList, Expression<Func<U, string>> property,
IList<string> values)
{
if (values == null || values.Count == 0)
return query;
Expression<Func<U, bool>> condition;
if (values.Count == 1)
condition = GetBooleanExpressionFromString(property, values.First());
else
condition = GetBooleanExpressionFromStringList(property, values);
Expression<Func<T, bool>> finalCondition = t => innerList.Invoke(t).Any(j => condition.Invoke(j));
return query.Where(finalCondition.Expand());
}
And then use it like this.
var query = Session.Query<User>();
query = query.FilterList(x => x.Addresses, y => y.Street, new [] { "Foo*", "*Bar", "*test*" });
return query;
Which is shorter and cleaner but restricted.
I have two expressions of type Expression<Func<T, bool>> and I want to take to OR, AND or NOT of these and get a new expression of the same type
Expression<Func<T, bool>> expr1;
Expression<Func<T, bool>> expr2;
...
//how to do this (the code below will obviously not work)
Expression<Func<T, bool>> andExpression = expr AND expr2
Well, you can use Expression.AndAlso / OrElse etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression in expr1 and expr2? If so, it is easier:
var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]);
This also works well to negate a single operation:
static Expression<Func<T, bool>> Not<T>(
this Expression<Func<T, bool>> expr)
{
return Expression.Lambda<Func<T, bool>>(
Expression.Not(expr.Body), expr.Parameters[0]);
}
Otherwise, depending on the LINQ provider, you might be able to combine them with Invoke:
// OrElse is very similar...
static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> left,
Expression<Func<T, bool>> right)
{
var param = Expression.Parameter(typeof(T), "x");
var body = Expression.AndAlso(
Expression.Invoke(left, param),
Expression.Invoke(right, param)
);
var lambda = Expression.Lambda<Func<T, bool>>(body, param);
return lambda;
}
Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for Invoke, but it is quite lengthy (and I can't remember where I left it...)
Generalized version that picks the simplest route:
static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
// need to detect whether they use the same
// parameter instance; if not, they need fixing
ParameterExpression param = expr1.Parameters[0];
if (ReferenceEquals(param, expr2.Parameters[0]))
{
// simple version
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(expr1.Body, expr2.Body), param);
}
// otherwise, keep expr1 "as is" and invoke expr2
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(
expr1.Body,
Expression.Invoke(expr2, param)), param);
}
Starting from .NET 4.0, there is the ExpressionVisitor class which allows you to build expressions that are EF safe.
public static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var parameter = Expression.Parameter(typeof (T));
var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
var left = leftVisitor.Visit(expr1.Body);
var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
var right = rightVisitor.Visit(expr2.Body);
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(left, right), parameter);
}
private class ReplaceExpressionVisitor
: ExpressionVisitor
{
private readonly Expression _oldValue;
private readonly Expression _newValue;
public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
{
_oldValue = oldValue;
_newValue = newValue;
}
public override Expression Visit(Expression node)
{
if (node == _oldValue)
return _newValue;
return base.Visit(node);
}
}
You can use Expression.AndAlso / OrElse to combine logical expressions, but you have to make sure the ParameterExpressions are the same.
I was having trouble with EF and the PredicateBuilder so I made my own without resorting to Invoke, that I could use like this:
var filterC = filterA.And(filterb);
Source code for my PredicateBuilder:
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);
}
}
And the utility class to substitute the parameters in a lambda:
internal class SubstExpressionVisitor : System.Linq.Expressions.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;
}
}
If you provider does not support Invoke and you need to combine two expression, you can use an ExpressionVisitor to replace the parameter in the second expression by the parameter in the first expression.
class ParameterUpdateVisitor : ExpressionVisitor
{
private ParameterExpression _oldParameter;
private ParameterExpression _newParameter;
public ParameterUpdateVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
{
_oldParameter = oldParameter;
_newParameter = newParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (object.ReferenceEquals(node, _oldParameter))
return _newParameter;
return base.VisitParameter(node);
}
}
static Expression<Func<T, bool>> UpdateParameter<T>(
Expression<Func<T, bool>> expr,
ParameterExpression newParameter)
{
var visitor = new ParameterUpdateVisitor(expr.Parameters[0], newParameter);
var body = visitor.Visit(expr.Body);
return Expression.Lambda<Func<T, bool>>(body, newParameter);
}
[TestMethod]
public void ExpressionText()
{
string text = "test";
Expression<Func<Coco, bool>> expr1 = p => p.Item1.Contains(text);
Expression<Func<Coco, bool>> expr2 = q => q.Item2.Contains(text);
Expression<Func<Coco, bool>> expr3 = UpdateParameter(expr2, expr1.Parameters[0]);
var expr4 = Expression.Lambda<Func<Recording, bool>>(
Expression.OrElse(expr1.Body, expr3.Body), expr1.Parameters[0]);
var func = expr4.Compile();
Assert.IsTrue(func(new Coco { Item1 = "caca", Item2 = "test pipi" }));
}
Nothing new here but married this answer with this answer and slightly refactored it so that even I understand what's going on:
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
ParameterExpression parameter1 = expr1.Parameters[0];
var visitor = new ReplaceParameterVisitor(expr2.Parameters[0], parameter1);
var body2WithParam1 = visitor.Visit(expr2.Body);
return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, body2WithParam1), parameter1);
}
private class ReplaceParameterVisitor : ExpressionVisitor
{
private ParameterExpression _oldParameter;
private ParameterExpression _newParameter;
public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
{
_oldParameter = oldParameter;
_newParameter = newParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (ReferenceEquals(node, _oldParameter))
return _newParameter;
return base.VisitParameter(node);
}
}
}
I combined some beautiful answers here to make it possible to easily support more Expression operators.
This is based on the answer of #Dejan but now it's quite easy to add the OR as well. I chose not to make the Combine function public, but you could do that to be even more flexible.
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.AndAlso);
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.Or);
public static Expression<Func<T, bool>> Combine<T>(Expression<Func<T, bool>> leftExpression, Expression<Func<T, bool>> rightExpression, Func<Expression, Expression, BinaryExpression> combineOperator)
{
var leftParameter = leftExpression.Parameters[0];
var rightParameter = rightExpression.Parameters[0];
var visitor = new ReplaceParameterVisitor(rightParameter, leftParameter);
var leftBody = leftExpression.Body;
var rightBody = visitor.Visit(rightExpression.Body);
return Expression.Lambda<Func<T, bool>>(combineOperator(leftBody, rightBody), leftParameter);
}
private class ReplaceParameterVisitor : ExpressionVisitor
{
private readonly ParameterExpression _oldParameter;
private readonly ParameterExpression _newParameter;
public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
{
_oldParameter = oldParameter;
_newParameter = newParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return ReferenceEquals(node, _oldParameter) ? _newParameter : base.VisitParameter(node);
}
}
}
Usage is not changed and still like this:
Expression<Func<Result, bool>> noFilterExpression = item => filters == null;
Expression<Func<Result, bool>> laptopFilterExpression = item => item.x == ...
Expression<Func<Result, bool>> dateFilterExpression = item => item.y == ...
var combinedFilterExpression = noFilterExpression.Or(laptopFilterExpression.AndAlso(dateFilterExpression));
efQuery.Where(combinedFilterExpression);
(This is an example based on my actual code, but read it as pseudo-code)
I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:
public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp)
{
var parameter = Expression.Parameter(sourceType);
var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
var left = leftVisitor.Visit(exp.Body);
var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
var right = rightVisitor.Visit(newExp.Body);
var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
}
I suggest one more improvement to PredicateBuilder and ExpressionVisitor solutions. I called it UnifyParametersByName and you can find it in MIT library of mine: LinqExprHelper. It allows for combining arbitary lambda expressions. Usually the questions are asked about predicate expression, but this idea extends to projection expressions as well.
The following code employs a method ExprAdres which creates a complicated parametrized expression, using inline lambda. This complicated expression is coded only once, and then reused, thanks to the LinqExprHelper mini-library.
public IQueryable<UbezpExt> UbezpFull
{
get
{
System.Linq.Expressions.Expression<
Func<UBEZPIECZONY, UBEZP_ADRES, UBEZP_ADRES, UbezpExt>> expr =
(u, parAdrM, parAdrZ) => new UbezpExt
{
Ub = u,
AdrM = parAdrM,
AdrZ = parAdrZ,
};
// From here an expression builder ExprAdres is called.
var expr2 = expr
.ReplacePar("parAdrM", ExprAdres("M").Body)
.ReplacePar("parAdrZ", ExprAdres("Z").Body);
return UBEZPIECZONY.Select((Expression<Func<UBEZPIECZONY, UbezpExt>>)expr2);
}
}
And this is the subexpression building code:
public static Expression<Func<UBEZPIECZONY, UBEZP_ADRES>> ExprAdres(string sTyp)
{
return u => u.UBEZP_ADRES.Where(a => a.TYP_ADRESU == sTyp)
.OrderByDescending(a => a.DATAOD).FirstOrDefault();
}
What I tried to achieve was to perform parametrized queries without need to copy-paste and with ability to use inline lambdas, which are so pretty. Without all these helper-expression stuff, I would be forced to create whole query in one go.
using System;
using System.Linq.Expressions;
namespace Extensions
{
public class Example
{
//How to use it
public static void Main()
{
Expression<Func<string, bool>> expression1 = exp => true;
Expression<Func<string, bool>> expression2 = exp => false;
Expression<Func<string, bool>> expression3 = ExpressionExtensions.AndAlso(expression1, expression2);
Expression<Func<string, bool>> expression4 = ExpressionExtensions.OrElse(expression1, expression2);
Expression<Func<string, bool>> expression = ExpressionExtensions.AndAlso(expression3, expression4);
}
}
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
ParameterExpression parameter1 = expr1.Parameters[0];
var visitor = new ReplaceParameterVisitor(expr2.Parameters[0], parameter1);
var body2WithParam1 = visitor.Visit(expr2.Body);
return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, body2WithParam1), parameter1);
}
public static Expression<Func<T, bool>> OrElse<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
ParameterExpression parameter1 = expr1.Parameters[0];
var visitor = new ReplaceParameterVisitor(expr2.Parameters[0], parameter1);
var body2WithParam1 = visitor.Visit(expr2.Body);
return Expression.Lambda<Func<T, bool>>(Expression.OrElse(expr1.Body, body2WithParam1), parameter1);
}
private class ReplaceParameterVisitor : ExpressionVisitor
{
private readonly ParameterExpression _oldParameter;
private readonly ParameterExpression _newParameter;
public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
{
_oldParameter = oldParameter;
_newParameter = newParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (ReferenceEquals(node, _oldParameter))
return _newParameter;
return base.VisitParameter(node);
}
}
}
}
One more solution (with no ExpressionVisitor) via one method and small enum to identity expression operation type
private static Expression<Func<T, bool>> BindExpressions<T>(ExpressionOperationType operationType, Expression<Func<T, bool>>[] expressionPredicates)
{
var filterExpressionPredicate = expressionPredicates.FirstOrDefault() ?? (x => false);
if (expressionPredicates.Length > 1)
for (int i = 1; i < expressionPredicates.Length; i++)
{
var expressionBody = Expression.Invoke(expressionPredicates[i], filterExpressionPredicate?.Parameters);
var handledExpressionUnits = operationType switch
{
ExpressionOperationType.AndAlso => Expression.AndAlso(filterExpressionPredicate.Body, expressionBody),
_ => Expression.OrElse(filterExpressionPredicate.Body, expressionBody),
};
filterExpressionPredicate = Expression.Lambda<Func<T, bool>>(handledExpressionUnits, filterExpressionPredicate.Parameters);
}
return filterExpressionPredicate;
}
enum ExpressionOperationType
{
AndAlso = 0,
OrElse = 1
}
For instance:
We have a model AuditLog
public class AuditLog
{
public Guid Id { get; set; }
public string OldValues { get; set; }
public string NewValues { get; set; }
public DateTime Timestamp { get; set; }
}
And we want to build specific query: search all audit records with key words "oranges", "cars", "birds" within the boundaries of date (Timestamp)
public IQueryable<AuditLog> BuildQuery()
{
var query = _context.AuditLogs.AsNoTracking();
var commonFilterList = new List<Expression<Func<AuditLog, bool>>>();
commonFilterList.Add(x => x.Timestamp >= DateTime.Now);
commonFilterList.Add(x => x.Timestamp <= DateTime.Now.AddDays(1));
//real world such simple filter case I would use way like:
//query = query
// .Where(x => x.Timestamp >= DateTime.Now)
// .Where(x => x.Timestamp <= DateTime.Now.AddDays(1));
//but this point we keep the example
//using AndAlso
query = query.Where(BindExpressions(ExpressionOperationType.AndAlso, commonFilterList.ToArray()));
//at this point we look at more useful example of using BindExpressions implementation via OrElse expression operation type
var specificFilterList = new List<Expression<Func<AuditLog, bool>>>();
var keyWordsToSearch = new List<string>() { "oranges", "cars", "birds" };
foreach (var keyWord in keyWordsToSearch)
{
//real world we would to use EF.Functions.Contains / EF.Functions.FreeText statements <- but it is question another scope
specificFilterList.Add(x => EF.Functions.Like(x.NewValues, $"%{keyWord}%"));
specificFilterList.Add(x => EF.Functions.Like(x.OldValues, $"%{keyWord}%"));
}
//using OrElse
query = query.Where(BindExpressions(ExpressionOperationType.OrElse, specificFilterList.ToArray()));
//as result we get commonFilterList AND specificFilterList
return query;
}
I think this works fine, isn't it ?
Func<T, bool> expr1 = (x => x.Att1 == "a");
Func<T, bool> expr2 = (x => x.Att2 == "b");
Func<T, bool> expr1ANDexpr2 = (x => expr1(x) && expr2(x));
Func<T, bool> expr1ORexpr2 = (x => expr1(x) || expr2(x));
Func<T, bool> NOTexpr1 = (x => !expr1(x));
Having a list of models:
List<string> models = new List<string>
{
"abcd1234",
"xycd9999",
"zzz999z",
"ros7777"
};
Having a filterer list:
List<string> filterer = new List<string>
{
"cd",
"9999"
};
I am trying using LINQ to get all the models that contains as part of their name the filterer items.
For this example:
"abcd1234" and "xycd9999" contains "cd"
"xycd9999" contains "9999"
therefore the LINQ operation will return a list of the two items: "abcd1234" and "xycd9999".
var filteredList = models
.Where(m => m.Contains("/*HERE WILL BE THE FILTERER ITEMS*/"))
.Distinct()
.ToList();
What is the correct syntax?
var filteredList = models
.Where(x => filterer.Any(y => x.Contains(y))
.ToList();
Distinct serves no purpose here, as the Where call doesn't introduce duplicates (unless of course models has duplicate values, and you want to remove those duplicates).
"Or" equivalent in Linq Where() lambda expression
Try to use PredicateBuilder as the link goes:
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);
}
}
In your case:
List<string> models = new List<string>
{
"abcd1234",
"xycd9999",
"zzz999z",
"ros7777"
};
List<string> filterer = new List<string>
{
"cd",
"9999"
};
var predicate = PredicateBuilder.False<string>();
foreach (string filter in filterer)
{
predicate = predicate.Or(f => f.Contains(filter));
}
var filteredList = models.AsQueryable().Where(predicate).ToList();
Using EF 6. Can someone tell me what am I doing wrong?
public List<SearchResult> SearchDocuments(List<SearchCriteria> searchCriterias)
{
List<SearchResult> results = new List<SearchResult>();
var fieldSettings = LoadCoordinateSystemFieldSettings(searchCriterias);
using (var context = CreateContext())
{
var tractsQuery = PredicateBuilder.False<v_UploadByTract_ActiveUploads>();
foreach (var searchCriteria in searchCriterias)
{
var queryBuilder = PredicateBuilder.True<v_UploadByTract_ActiveUploads>();
// tractsQuery
if (searchCriteria.StateAPI.HasValue)
queryBuilder = queryBuilder.And(a => a.StateAPI == searchCriteria.StateAPI.Value);
if (searchCriteria.CountyAPI.HasValue)
queryBuilder = queryBuilder.And(a => a.CountyAPI == searchCriteria.CountyAPI.Value);
// ...
// ... many more similar IF-ANDs
// ...
tractsQuery = tractsQuery.Or(queryBuilder);
}
var searchQuery = context.v_UploadByTract_ActiveUploads.AsExpandable().Where(tractsQuery).ToList();
//.Select(a => SearchResult.Create(a));
//results.AddRange(searchQuery.ToList());
}
return results;
}
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);
}
}
quetzalcoatl thanks for the answer. The other post did it. From else where I had come across AsExpandable() and overlooked this one thinking it's talking about the same. After reading your post and re-reading the discussion, this worked. Since your post shows up as "comment", I am unable to mark that as the answer.
Any suggestions on how to consolidate those nasty IFs.
C# PredicateBuilder Entities: The parameter 'f' was not bound in the specified LINQ to Entities query expression
For anyone else googling into here, my solution was to Visit a modified expression before returning it into the expression tree. This bound the lambda parameter.
I have the following object
public Cell {
public string CategoryId {get; set;}
public DateTime FromTime {get; set}
public DateTime ToTime {get; set}
}
I have a DB table that is called Item that looks like this:
Item
-------------------------
CategoryId LastUpdated
Now in the code I have a list of Cell List<Cell> ToBeFetchedFromDB that contains more than one Cell, suppose the list contains Foo and Bar, I want to dynamically build a query like this BY INTERATING THROUGH THE COLLECTION ToBeFetchedFromDB WITHIN MY LINQ TO SQL QUERY instead of statically constructing the query:
from x in Item
where x.CategoryId == Foo.CategoryId && Foo.FromTime < x.LastUpdated < Foo.ToTime
|| x.CategoryId == Bar.CategoryId && Bar.FromTime < x.LastUpdated < Bar.ToTime
select x
I have been trying but can't figure it out :(
Thanks guys!
Using PredicateBuilder you can go through each item in your list using a foreach and add a new option for your filter:
var filter = PredicateBuilder.False<Item>();
foreach (var cell in ToBeFetchedFromDB)
{
filter = PredicateBuilder.Or(filter, item =>
item.CategoryId == cell.CategoryId &&
cell.FromTime < item.LastUpdated &&
item.LastUpdated < cell.ToTime);
}
var query = Item.Where(filter);
A copy of PredicateBuilder from the link:
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);
}
}