How can I build Linq query with dynamic OR statements?

前端 未结 1 704
青春惊慌失措
青春惊慌失措 2021-01-12 00:34

The following code:

var dynamicQuery = from a in _context.Users select a;
string[] args = new string[] { \"aa\", \"bb\", \"cc\" };
foreach (string word in ar         


        
相关标签:
1条回答
  • 2021-01-12 01:00

    You don't need to loop 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 quite deep stacks (with one delegate calling another calling another etc). Where the specific situation allows you to use Any, that would usually be a better approach.

    I would expect Any to work in most situations where you've got a collection of items to potentially match against... the non-Any approach is approprate for "in some situations, anyone over 18 is fine... in some situations anyone with a last name beginning with "G" is appropriate, etc.

    0 讨论(0)
提交回复
热议问题