LINQ to Objects has a dynamic where clause.

c# dynamic-linq linq linq-to-objects

Question

I know there are a lot of examples of this on the web, but I can't seem to get this to work.

Let me try to set this up, I have a list of custom objects that I need to have limited on a range of values.

I have a sort variable that changes based on some action on the UI, and I need to process the object differently based on that.

Here is my object:

MyObject.ID - Just an identifier
MyObject.Cost - The cost of the object.
MyObject.Name - The name of the object.

Now I need to filter this based on a range in the cost, so I will have something similar to this, considering that I could be limiting by Either of my bottom two properties.

var product = from mo in myobject 
              where mo.Cost <= 10000

or

var product = from mo in myobject
              where mo.Name equals strName

Now I have the dynamic linq in my project, but I'm not figuring out how to get it to actually work, as when I do some of the examples I am only getting:

Func<Tsourse>bool> predicate

as an option.

Update: I am trying to find a solution that helps me Objectify my code, as right now it is a lot of copy and paste for my linq queries.

Update 2: Is there an obvious performance difference between:

var product = from mo in myobject 
... a few joins ...
where mo.Cost <= 10000

and

var product = (from mo in myobject 
... a few joins ...)
.AsQueryable()
.Where("Cost > 1000")
1
0
2/18/2015 4:46:57 AM

Accepted Answer

Maybe not directly answering your question, but DynamicQuery is unnecessary here. You can write this query as:

public IEnumerable<MyObject> GetMyObjects(int? maxCost, string name)
{
    var query = context.MyObjects;
    if (maxCost != null)
    {
        query = query.Where(mo => mo.Cost <= (int)maxCost);
    }
    if (!string.IsNullOrEmpty(name))
    {
        query = query.Where(mo => mo.Name == name);
    }
    return query;
}

If the conditions are mutually exclusive then just change the second if into an else if.

I use this pattern all the time. What "Dynamic Query" really means is combining pure SQL with Linq; it doesn't really help you that much with generating conditions on the fly.

2
1/8/2010 3:29:53 PM

Popular Answer

using System.Linq;

var products = mo.Where(x => x.Name == "xyz");

var products = mo.Where(x => x.Cost <= 1000);

var products = mo.Where(x => x.Name == "xyz" || x.Cost <= 1000);


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow