How can I create a Linq query with dynamic OR operations?

The following code:

var dynamicQuery = from a in _context.Users select a; string[] args = new string[] { "aa", "bb", "cc" }; foreach (string word in args) dynamicQuery = dynamicQuery.Where(x => x.Name.Contains(word)); return dynamicQuery.ToList(); 

Lets me create a Linq query with a dynamic list of AND expressions.

But suppose I wanted to do the same, only with a dynamic list of expressions OR ?

+7
source share
1 answer

You don’t have to go in cycles at all:

 return _context.Users.Where(x => args.Any(word => x.Name.Contains(word))); 

EDIT: More generally, you can use:

 Func<User, bool> predicate = user => false; foreach (var item in items) { var predicateCopy = predicate; predicate = user => predicateCopy(user) || someOtherCondition; } return query.Where(predicate); 

This will end up with fairly deep stacks (with one delegate calling another call to another, etc.). If a particular situation allows you to use Any , this will usually be the best approach.

I would expect Any to work in most situations where you have a set of elements that could potentially be the same ... the non Any approach is suitable for "in some situations, who are over 18 ... in some situations, anyone who has a last name starting with "G", suitable, etc.

+10
source

All Articles