Dynamic query in LINQ

后端 未结 5 1311
不思量自难忘°
不思量自难忘° 2021-02-11 06:56

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.

提交回复
热议问题