Clarence Klopfstein
Clarence Klopfstein

Reputation: 4852

Dynamic where clause in LINQ to Objects

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")

Upvotes: 0

Views: 6459

Answers (3)

Stan R.
Stan R.

Reputation: 16065

Read this great post on DLINQ by ScottGu

Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)

You would need something like

var product = myobject.Where("Cost <= 10000");
var product = myobject.Where("Name = @0", strName);

If you downloaded the samples you need to find the Dynamic.cs file in the sample. You need to copy this file into your project and then add using System.Linq.Dynamic; to the class you are trying to use Dynamic Linq in.

EDIT: To answer your edit. Yes, there is of course a performance difference. If you know the variations of filters beforehand then I would suggest writing them out without using DLINQ.

You can create your own Extension Method like so.

 public static class FilterExtensions
    {
        public static IEnumerable<T> AddFilter<T,T1>(this IEnumerable<T> list, Func<T,T1, bool> filter,  T1 argument )
        {
            return list.Where(foo => filter(foo, argument) );
        }
    }

Then create your filter methods.

        public bool FilterById(Foo obj, int id)
        {
            return obj.id == id;
        }

        public bool FilterByName(Foo obj, string name)
        {
            return obj.name == name;
        }

Now you can use this on an IEnumerable<Foo> very easily.

    List<Foo> foos = new List<Foo>();
    foos.Add(new Foo() { id = 1, name = "test" });
    foos.Add(new Foo() { id = 1, name = "test1" });
    foos.Add(new Foo() { id = 2, name = "test2" });

    //Example 1
    //get all Foos's by Id == 1
    var list1 = foos.AddFilter(FilterById, 1);

    //Example 2
    //get all Foo's by name ==  "test1"
    var list2 = foos.AddFilter(FilterByName, "test1");

    //Example 3
   //get all Foo's by Id and Name
   var list1 = foos.AddFilter(FilterById, 1).AddFilter(FilterByName, "test1");

Upvotes: 1

Kris Krause
Kris Krause

Reputation: 7326

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

Upvotes: 1

Aaronaught
Aaronaught

Reputation: 122644

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.

Upvotes: 2

Related Questions