I want to accept a string array of where conditions from the client like field == value.
It would be really nice to create a specification object that could accept the string in the constructor and output a lambda expression to represent the Where clause. For example, I could do the following:
var myCondition = new Specification<Product>( myStringArrayOfConditions);
var myProducts = DB.Products.Where( myCondition);
How could you turn "name == Jujyfruits" into DB.Products.Where(p => p.name == "JujyFruits")?
You can use
Product.namefrom the stringnameandExpressionclass to manually create a lambda expression.Note that the following code example will only work for
Equals (==)operations. However, it is easy to generalize to other operations as well (split on whitespace, parse the operator and choose the appropriate Expression instead ofExpression.Equal).About the constructor thing: Since
Func<T, TResult>is sealed, you cannot derive from it. However, you could create an implicit conversion operator that translatesSpecification<T>intoFunc<T, bool>.