LINQ lambda expression append OR statement

后端 未结 5 1464
攒了一身酷
攒了一身酷 2020-12-21 03:39

If I want to append a AND statement to my query, I can do:

query = query.Where(obj=>obj.Id == id);

if(name.HasValue)
  query = query.Where(obj=>obj.Na         


        
5条回答
  •  眼角桃花
    2020-12-21 04:29

    I would use gdoron's solution, but if it seems unpractical for larger sets of queries, a slightly more complicated solution containing set operations might help you:

    var queryById = query.Where(obj => obj.Id == id);
    var queryByName = query.Where(obj => obj.Name == name);
    query = queryById.Union(queryByName);
    

    It gets much more difficult if your original query contains duplicate items.

    Another way may be using Expression to formulate your queries. You can modify the expression tree before executing it, so you can add more conditions to the Where sub-tree. That is a whole lot of work and it's an overkill on 99.9% (rough estimate :) ) of cases.

提交回复
热议问题