Dynamic where clause in LINQ - with column names available at runtime

后端 未结 4 2189
没有蜡笔的小新
没有蜡笔的小新 2021-02-06 02:47

Disclaimer: I\'ve solved the problem using Expressions from System.Linq.Expressions, but I\'m still looking for a better/easier way.

Consider the following situation :

4条回答
  •  Happy的楠姐
    2021-02-06 03:22

    You can turn your where clauses on and off using some logic expressions.

    //Turn on all where clauses
    bool ignoreFirstName = false;
    bool ignoreLastName = false;;
    bool ignoreAddress = false;
    
    //Decide which WHERE clauses we are going to turn off because of something.
    if(something)
        ignoreFirstName = true; 
    
    //Create the query
    var queryCustomers = from c in db.Customers 
        where (ignoreFirstName || (c.ContactFirstName.Contains("BlackListed")))
        where (ignoreLastName || (c.ContactLastName.Contains("BlackListed")))
        where (ignoreAddress || (c.Address.Contains("BlackListed"))
        select j;  
    

    If ignoreFirstName is true in the query then the condition on the other side of the or statement will be ignored.

提交回复
热议问题