How to Create a Linq Statement from a String
Posted: 11/4/2009 1:21:26 PM
Almost two years ago ScottGu posted some really awesome code that lets
you create dynamic where clauses in Linq - meaning you could use a
string builder to create your where clause just like the good 'ole days
when ad-hoc sql was all the rage. You're going to be better off if you
can build a predicate using lambdas, but sometimes its a real pain the
the rear to build a proper predicate (Func<T, bool> or
Predicate<T>). Building a predicate properly typically becomes
difficult when you're giving your users some mechanism to build their
own filter for their data.
The problem I had with ScottGu's code
is that the extension methods only worked off IQueryable<T>, and
well, sometimes you would like to create a dynamic where clause for a
datasource that didn't come from an IQueryProvider like LinqToSql.
Sometime you want to create a dynamic where clause for a plain old
IEnumerable<T>.
So, I took the time to dig through
ScottGu's pretty complicated code and created a handful of methods that
help you generate useful dynamic functions - including dynamic
"OrderBy" and "Where" extension methods for IEnumerable<T>.
I've attached a single common file that includes both ScottGu's code, as well as my own.
Download my code here:
DynamicLinqExtensions.zip (15 KB)
Examples:
IEnumerable<Person> allPeople = GetAllPeople();
foreach(var person in allPeople.Where("Age > 10").OrderBy("Age"))
{
//notice the above arguments are strings and not lambdas
//this makes it a lot easier to build everything ad-hoc
Console.WriteLine(person.Age + " - " + person.FirstName);
}
I also included a method called CreateValueExpression, that will evaluate an expression on any object and return the result.
var fullName = DynamicLinqExtensions.CreateValueExpression<Person,string>("First + \" \" + Last");
//outputs "Jon von Gillern"
Console.WriteLine(fullName(new Person { First = "Jon", Last = "von Gillern" }));
You can find the Gu's original blog post here:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
As always, Kicks and Shoutouts are appreciated!
Tags: Tips and Tricks