3

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

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
user466663
  • 815
  • 4
  • 18
  • 40

3 Answers3

4

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.

Mike Goodwin
  • 8,810
  • 2
  • 35
  • 50
  • The dynamic linq library works only for integers and not strings, or atleast I have not seen any samples using string. There are so many articles and blogs on this subject, and all of them use integers as example! The AccountId I have to query is a string. – user466663 Mar 13 '12 at 15:54
  • I'm not sure what you mean by "works only for integers and not strings". If you look at the documentation for the dynamic query language you will see that it works for any type - not just ints. In the screenshot of the API documetnation near the top of the link I suggested, it shows an example of using strings. I updated my answer a little bit to show this. – Mike Goodwin Mar 15 '12 at 08:30
1

Given a class such as:

public class foo
{
  public int AccountID {get;set;}
}

You should be able to do something like this:

Expression<Func<foo, bool>> filter = f => f.AccountID == 1000;

And then pass that as your query. If it is really needed as a string you can do this:

filter.ToString();
Tony Ranieri
  • 1,479
  • 1
  • 18
  • 32
0

//By Using this library

using System.Linq.Dynamic.Core;

InventoryList = Repository.GetAll(); // IQueryable

string filterString = "UnitPrice > 10 And Qty>100 OR Description.Contains("Dairy")";

var filteredGenericList = InventoryList.Where(filterString);

Shahid Malik
  • 163
  • 13