Use of Lambda Expression to Create Complicated Query

.NET FX introduces a powerful weapon for creating the compact, breezy and elegant code in your project. The weapon’s name is as complicated as the mathematical stuff, called Lambda expression.

As the name implies, the great convenience comes great complication inside. Lambda expression is too important to understand, it is useful and I think it is good to know how it works. Well, it’s not as complicated as we think, just a little bit confusing when using it.

First of all, Lambda is used for 2 purposes. 1 is to simplify delegation, 2 is to create expression tree. In my case, I need to create lambda expression to create dynamic query.

Imagine the following usecase:

In your product table, there is a field called “Tags” and it’s used for storing the CSV (comma separated value) like “car, mazda, suv, luxury”, you have many records:

Product Table: (Table name: ProductTable)

ID    ProductName    Tags
1    Tow bar        car,mazda,suv,luxury
2    Cup holder    car,luxury
3    Phone holder    car,mazda
4    FM Transmitter    car,suv
5    Queens bed    luxury
6    DVD Burner    car,BMW,x5,luxury

When your searching criteria is
“mazda” and “luxury”, the following records would be selected out:

ID    ProductName    Tags
1    Tow bar        car,mazda,suv,luxury
2    Cup holder    car,luxury
3    Phone holder    car,mazda
5    Queens bed    luxury
6    DVD Burner    car,BMW,x5,luxury

In ancient SQL age, you would probably write a SQL like this:

string SQL = “SELECT * FORM ProductTable WHERE Tags LIKE’%mazda%’ OR Tags LIKE ‘%luxury%’”;

It is IMpossible to create SQL like above except the project scope tells you the fixed keywords that would be used, the keywords should flexible. Then the code would be as much as:

string[] tags = new string[]{“mazda”, “luxury”};
string SQL = “SELECT * FROM ProductTable WHERE 1=1″;
foreach(string tag in tags)
{
SQL += string.format(@” AND Tags like ‘%{0}%’”, tag);
}

You must be very exciting that your code supports as many keywrods as it can. (I did before, I mean I would be very exciting when the code filled with logical stuff, LOL, of course, not now, that’s what geek did before~ )

Back to the reality, to the modern age, with the lambda expression, what you need to do is:

(pre-condition: you have created corresponding domain model which mapped to the database.)
The domain object or entity would look like:

[Table("ProductTable")] Class ProductTable{
[Column]public int Id{get; set;}
[Column]public string ProductName{get; set;}
[Column]public string Tags{get; set;}
}

to fullfill the same kind of logic as the stone-aged people do, you just need to

DataContext db = new DataContext(“<connection-string>”);
Table<ProductTable> table = db.GetTable<ProductTable>();
string tag1 = “mazda”;
string tag2 = “luxury”;
var data = table.where(x=>x.Tags.Contains(tag1)).where(x=>x.Tags.Contains(tag2)) select new ProductTable;
return data.AsQueryable();

Since so far, you still feel comfortable with this, but after minute, you would probably wanna go back stone age, how do we dynamically create the query in this case? Unfortunately, there is no short-cut for this, but many people provide lots of solutions on the Internet. We can either download some source codes about dynamically query on Internet or just grab the codes from the blogger’s website.( Most of time, you can’t use all of their codes posted on the blog, the codes are broken and bad structure, remember what Koumei always suggests, absorb the mind from the other coders, do not copy the code they provided. )

But in here, I would rather to use Expression Tree to implement the dynamic query.

First of all, we need to create an expression, because it would be applied to IQueryable.Where(Expression<Func<ProductTable, bool>> expression), so the expression should be defined as:

public static System.Linq.Expressions.Expression<Func<ProductTable, bool>> ApplyTags(IEnumerable<string> tags) //parameter is the collection of tags
{
ParameterExpression c = Expression.Parameter(typeof(ProductTable), “c”); //Get the parameter from Func<ProductTable, bool>, remember? this is the advanced and lazy version of delegation, we need to craete ParameterExpression to hold this
var tagsProperty = Expression.Property(c, typeof(ProductTable).GetProperty(“Tags”)); //Here is the expression for get the Tags value from ProductTable object
Type[] ContainsTypes = new Type[1];
ContainsTypes[0] = typeof(string);
System.Reflection.MethodInfo myContainsInfo = typeof(string).GetMethod(“Contains”, ContainsTypes);
//Create the expression collection (based on the tags collection from parameter)
List<Expression> myTagExpressions = new List<Expression>();
foreach (var t in tags)
{
myTagExpressions.Add(Expression.Call(Expression.Call(tagsProperty, “ToString”, null, null), myContainsInfo, Expression.Constant(t)));
}
Expression OrExpression = null;
foreach (Expression myTagExpression in myTagExpressions)
{
if (OrExpression == null)
{
OrExpression = myTagExpression;
}
else
{
//Need to implement OR relationship among all the expressions
OrExpression = Expression.Or(myTagExpression, OrExpression);
}
}
//This is how Expression would be extracted to expression tree later on.
Expression<Func<ProductTable, bool>> predicate = Expression.Lambda<Func<ProductTable, bool>>(OrExpression, c);
return predicate;
}

Again, you can’t copy the code, since you would NOT have the same object like ProductTable and the same “Tags” property as I do. Luckily, you still can copy the code that I provide later, which is using the magic of template or generic programming. Before that, let us see how to use it:

IQueryable all = table.Where(ApplyTags(new List{“mazda”,”luxury”})).AsQueryable();

Since so far, I am 100% sure you can do it like refactoring, re-structuring to optimize your code. However, I would like to provide the code which can be general used:

public static System.Linq.Expressions.Expression<Func<T, bool>> ApplyFilter<T>(IEnumerable<string> filters, string property)
{
//Get parameter
ParameterExpression c = Expression.Parameter(typeof(T), “c”);
//Get property from <T>
var tagsProperty = Expression.Property(c, typeof(T).GetProperty(property));
Type[] ContainsTypes = new Type[1];
ContainsTypes[0] = typeof(string);
System.Reflection.MethodInfo myContainsInfo = typeof(string).GetMethod(“Contains”, ContainsTypes);
List<Expression> myTagExpressions = new List<Expression>();
foreach (var t in filters)
{
myTagExpressions.Add(Expression.Call(Expression.Call(tagsProperty, “ToString”, null, null), myContainsInfo, Expression.Constant(t)));
}
Expression OrExpression = null;
foreach (Expression myTagExpression in myTagExpressions)
{
if (OrExpression == null)
{
OrExpression = myTagExpression;
}
else
{
OrExpression = Expression.Or(myTagExpression, OrExpression);
}
}
Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(OrExpression, c);
return predicate;
}

The usage is similiar:

IQueryable all = table.Where(ApplyFilter<ProductTable>(new List{“mazda”,”luxury”}, “Tags”)).AsQueryable();

Not that hard, right?

Enjoy the powerful weapon, but don’t hurt yourself, bacause the deadline is ahead!

6    DVD Burner    car,BMW,x5,luxury

2 thoughts on “Use of Lambda Expression to Create Complicated Query”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">