Dynamic query in LINQ

后端 未结 5 695
甜味超标
甜味超标 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:44

    You can use the fluent interface and add a new Where clause fpr each condition. Something like:

     var result = from cus in customers select cus;
     if(!string.IsNullOrEmpty(name))
             result= result.Where(p => p.Name == name);
    

    EDIT upon hte comment:

    if you are querying over a collection in memory, you could retrieve the properties using reflection.

    private Customer[] GetCustomers(Dictionary attributes)
    {
          var result = from cus in customers select cus;    
    
          foreach(string key in attributes.Keys)
                 result= result.Where(p => GetProperty(p, key )== attributes[key]);
    
             return result.ToList();    
    }
    

    Supposing GetProperty retrieve the property by reflection.

    Using Linq2Sql this method will result in retrieving all record an then iterating over them using reflection.

提交回复
热议问题