LINQ is it possible to add where clauses dynamically

前端 未结 5 1381
青春惊慌失措
青春惊慌失措 2021-01-05 02:36

I want to search my db with different keys. According to the input, there may be 1 key to 10 keys. Is there a way to add OR/AND clauses to my Linq query dynamically?

5条回答
  •  我在风中等你
    2021-01-05 03:10

    You can do something like this. Remember it may casue some overhead

     var students = ctx.Students;
    
     if (!String.IsNullOrWhiteSpace(SearchParams.Name))
          students = from s in students where s.Name.StartsWith(SearchParams.Name)
    
     if (!String.IsNullOrWhiteSpace(SearchParams.Surname))
          students = from s in students where s.Surname.StartsWith(SearchParams.Surname)
    

提交回复
热议问题