Tuesday, September 30, 2008

Dynamic Where Clause in LINQ

I had a friend who wanted to do a dynamic where clause. The problem he ran into was adjusting the predicate when you don't know the properties that you are going to query. I have a solution that may be of help to you.

Suppose you want to do something like the following:

YourTypeDataContext db=new YourTypeDataContext();
var users=from u in db.Users where (dynamic) select u;

The problem is that the properties aren't immediately known. A solution is to use reflection like the following:

string dynamicProperty="DynamicPropertyName";
string val="valToSearchFor";
Type t=typeof(User); //User is a type generated by the dbml for the Users table
System.Reflection.PropertyInfo p=t.GetProperty(dynamicProperty);
users=users.Where( u=> Convert.ToString( p.GetValue( u, null ) ) == val);

The first thing I'm doing is getting the type of User so that I can reflect and get the property names. Then I'm setting a string (dynamicProperty) to any property I want to search for. A method that took this and the value to search for as parameters would probably be the best way for you to do this.

I wrapped Convert.ToString around t.GetProperty to account for null values, and set my IQueryable return value to the same variable and voila!

I will adjust this post with a more dynamic approach and account for multiple properties in the near future. Hope it helps!