Home > Net >  Build a where statement from a list in Entity Framework
Build a where statement from a list in Entity Framework

Time:02-18

I have a list of strings that I want to use to create a where statement in Entity Framework. For example if I have a list of strings.

List<string> cars = = new(){"car1","car2", "car3"};

I want to build a where clause dynamically from the list

query = query.Where(a => a.car == "car1" || a.car == "car2" || a.car == "car3");

CodePudding user response:

Using LINQKit, you can create some extension methods to handle this automatically:

// searchTerms - IEnumerable<TSearch> where one must match for a row
// testFne(row,searchTerm) - test one of searchTerms against a row
// dbq.Where(r => searchTerms.Any(s => testFne(r,s)))
public static IQueryable<T> WhereAny<T, TSearch>(this IQueryable<T> dbq, IEnumerable<TSearch> searchTerms, Expression<Func<T, TSearch, bool>> testFne) =>
    dbq.AsExpandable().Where(searchTerms.AnyIs(testFne));
public static IQueryable<T> WhereAny<T, TSearch>(this IQueryable<T> dbq, Expression<Func<T, TSearch, bool>> testFne, IEnumerable<TSearch> searchTerms) =>
    dbq.AsExpandable().Where(searchTerms.AnyIs(testFne));
public static IQueryable<T> WhereAny<T, TSearch>(this IQueryable<T> dbq, Expression<Func<T, TSearch, bool>> testFne, params TSearch[] searchTerms) =>
    dbq.AsExpandable().Where(searchTerms.AnyIs(testFne));

// searchTerms - IEnumerable<TSearch> where one must match for a row
// testFne(row,searchTerm) - test one of searchTerms against a row
// r => searchTerms.All(s => testFne(r,s))
public static Expression<Func<T, bool>> AnyIs<T, TSearch>(this IEnumerable<TSearch> searchTerms, Expression<Func<T, TSearch, bool>> testFne) {
    var pred = PredicateBuilder.New<T>();
    foreach (var s in searchTerms)
        pred = pred.Or(r => testFne.Invoke(r, s));

    return pred;
}

Then you can just do:

query = query.WhereAny(cars,(a, c) => a.car == c);

You can also roll your own simplified LINQKit light environment to handle the expression construction.

  • Related