Linq – How to use a string in the linq where clause

dynamiclinq

I am trying to send a Linq query as a string to a method to be used in a where clause. Since IEnumerable wouldn't work for this, I have converted my IEnumerable to IQueryable and still it throws error. The following is the code:

public static void  FilterData(string Query)
        {
            if((List<MemberMaintenanceData>)HttpContext.Current.Session["Allmembers"] != null)
            {
                //Get the IEnumerable object colection from session
                var data = (List<MemberMaintenanceData>) HttpContext.Current.Session["Allmembers"];
                //Convert it to IQueryable
                IQueryable<MemberMaintenanceData> queryData = data.AsQueryable();
                //This line doesn't compile!!
                queryData = queryData.Where(Query);
                HttpContext.Current.Session["Allmembers"] = queryData.AsEnumerable().ToList();
            }

        }

I intended passing "a => a.AccountId == 1000" as Query

Best Answer

There is a free (and open source) library, provided by Microsoft for parsing strings into Lambda expressions that can then be used in Linq queries. It also contains versions of the standard query operators such as Where() that take a string parameter. You can find it described in Scott Guthries blog post on Dynamic Linq.

For example, you can do queries like this (adapted from a snippet from the Scott guthrie link)

// imagine these have come from a drop down box or some other user input...
string thingToSelectBy = "City";
string citySelectedByUser = "London";
int minNumberOfOrders = 10;

string whereClause = String.Format("{0} = @0 and Orders.Count >= @1", thingToSelectBy);

var query = db.Customers
       .Where(whereClause, citySelectedByUser, minNumberOfOrders)
       .OrderBy("CompanyName")
       .Select("new(CompanyName as Name, Phone");

The Where clause in thisw code snippet shows how you create a where clause using a parameterised string and then dynamically inject values for the parameters at run time, for example, based on user input. This works for parameters of any type.

In your example, the where clause would be

whereClause = "AccountId = 1000";

So in effect you would be doing something like

var newFilteredQueryData = queryData.Where("AccountId = 1000");

That link also contains the location where you can download the source code and a comprehensive document describing the dynamic query API and expression language.