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

后端 未结 4 2147
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  梦毁少年i
    2021-02-06 03:19

    @Geoff has the best option, justing Dynamic LINQ.

    If you want to go the way of building queries at runtime using Lambda though I'd recomment that you use the PredicateBuilder (http://www.albahari.com/nutshell/predicatebuilder.aspx) and have something such as this:

    Expression> pred = null; //delcare the predicate to start with. Note - I don't know your type so I just used T 
    if(blacklistFirstName){
      pred = p => p.ContactFirstName.Contains("Blacklisted");
    }
    if(blacklistLastName){
      if(pred == null){
        pred = p => p.ContactLastName.Contains("Blacklisted"); //if it doesn't exist just assign it
      }else{
        pred = pred.And(p => p.ContactLastName.Contains("Blacklisted"); //otherwise we add it as an And clause
      }
    }
    

    And so on for all the columns you want to include. When you get to your query you just need something like this:

    var results = db.Customers.Where(pred).Select(c => c);
    

    I've used this to do building of LINQ for searching where there are about 20 different options and it produces really good SQL.

提交回复
热议问题