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

后端 未结 4 2143
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  生来不讨喜
    2021-02-06 03:27

    var query = from C in db.Customers select c;
    
    if (seachFirstName)
             query = query.Where(c=>c.ContactFirstname.Contains("Blacklisted"));
    
    if (seachLastName)
             query = query.Where(c=>c.ContactLastname.Contains("Blacklisted"));
    
    if (seachAddress)
             query = query.Where(c=>c.Address.Contains("Blacklisted"));
    

    Note that they aren't mutually exclusive.

提交回复
热议问题