Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic LINQ OR Conditions

Tags:

linq

I'm looking to use LINQ to do multiple where conditions on a collection similar to

IEnumerable<Object> items;
items.Where(p => p.FirstName = "John");
items.Where(p => p.LastName = "Smith");

except for rather than having multiple AND conditions (as with this example), I'd like to have multiple OR conditions.

EDIT Sorry, to clarify I don't know how many of these conditions I will have so

items.Where(p => p.FirstName = "John" || p => p.LastName = "Smith")

won't work.

Basically, here's what I'm trying to do:

foreach(var name in names)
{
    items = items.Where(p => p.Name == name);
}
like image 932
Kyle Avatar asked Dec 08 '10 18:12

Kyle


People also ask

What is Dynamic LINQ?

The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.

Is Dynamic LINQ safe?

And Dynamic Linq is actually composed from strings, therefore it is potentially prone to attack by injection. Obviously, the attacker will have to be aware of the fact that you are using DynamicLinq and could attack only preparing the data so it results in valid malicious Dynamic Linq query.

What is System LINQ dynamic core?

System.Linq.Dynamic is the Microsoft assembly for the .Net 4.0 Dynamic language functionality. System.Linq.Dynamic.Core is a .NET Core port of the the Microsoft assembly for the .Net 4.0 Dynamic language functionality.


1 Answers

Use PredicateBuilder:

Suppose you want to write a LINQ to SQL or Entity Framework query that implements a keyword-style search. In other words, a query that returns rows whose description contains some or all of a given set of keywords...

The ideal approach is to dynamically construct a lambda expression tree that performs an or-based predicate.

Of all the things that will drive you to manually constructing expression trees, the need for dynamic predicates is the most common in a typical business application. Fortunately, it’s possible to write a set of simple and reusable extension methods that radically simplify this task. This is the role of our PredicateBuilder class...

like image 161
as-cii Avatar answered Nov 03 '22 17:11

as-cii