Linq optional parameters

后端 未结 2 1461
日久生厌
日久生厌 2021-01-05 07:34

I have a linq query. I have a bunch of parameters from a form I collect where I need to filter based of fields the user is searching for.

IQueyable

        
2条回答
  •  长情又很酷
    2021-01-05 08:10

    If the query doesn't include a particular field, you don't need to include it as part of the where clause at all:

    IQueyable user = from user in edmxObject.Users;
    
    if (model.FirstName != null) 
        users = users.Where(user => user.FirstName.Contains(model.FirstName)
    
    if (/* age is searched for */) 
        users = users.Where(user => user.Age == model.Age);
    

    You can conditionally nest predicates this way to ensure you have only the conditions you really need.

提交回复
热议问题