Dynamic query in LINQ

后端 未结 5 701
甜味超标
甜味超标 2021-02-11 06:47

How do I write a dynamic query for Linq, if I have say Customer class which holds the fields:

string name
string address
int phoneno

I have to

5条回答
  •  感情败类
    2021-02-11 07:33

    Here you go:

    var result = from customer in Customers
                 where string.IsNullOrEmpty(phoneNo) || customer.PhoneNo == phoneNo
                 where string.IsNullOrEmpty(address) || customer.Address == address
                 select customer;
    

    If you're concerned that this generate the optimal SQL query underneath, as always you should attach a SQL Query Analyzer and check. But I believe the expression parser in Linq To Sql will collapse down the where clauses as appropriate based on the value of the arguments.

提交回复
热议问题