user466663
user466663

Reputation: 845

How to use a string in the linq where clause?

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

Upvotes: 3

Views: 22236

Answers (3)

Shahid Malik
Shahid Malik

Reputation: 171

//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);

Upvotes: 0

Mike Goodwin
Mike Goodwin

Reputation: 8880

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.

Upvotes: 4

Tony Ranieri
Tony Ranieri

Reputation: 1567

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();

Upvotes: 1

Related Questions