Binod
Binod

Reputation: 313

Dynamic Linq Query and Expression

I would like to build a dynamic query but failed to get the required result. Please see the below code. I have tried using two different approach.

  1. Simple Linq , the result is "resultUsingLing" in the below code.
  2. Dynamic Linq the result is "resultUsingDynamicLinq" in the below code.

I want to get the same result from both "resultUsingLing" and "resultUsingDynamicLinq". The resultUsingDynamicLinq returns no value.

public class Test
{
    public string Name { get; set; }
    public string Address { get; set; }
}
public class Program
{
    public static void Main()
    {
        List<Test> testList = new List<Test>() 
        {
            new Test() { Address = "Address", Name = "Name" },
            new Test() { Address = "Address1", Name = "Name1" }, 
            new Test() { Address = "Address2", Name = "Name2" }, 
            new Test() { Address = "Address3", Name = "Name3" },
            new Test() { Address = "Address4", Name = "Name4" } 
        };
        IQueryable<Test> queryableTestData = testList.AsQueryable<Test>();
        var resultUsingLing= queryableTestData.Where(x => x.Address.Equals("Address1"));

        string property = "Address";
        string value = "Address1";
        var type = typeof(Test);
        var pe1 = Expression.Parameter(type, "p");
        var propertyReference = Expression.Property(pe1, property);
        var constantReference = Expression.Constant(value);
        var resultUsingDynamicLinq= Expression.Lambda<Func<Test, bool>>
            (Expression.Equal(propertyReference, constantReference),
            new[] { pe1 }).Compile();
    }
}

Upvotes: 0

Views: 204

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

That's because you're not using the expression you've created anywhere.

And btw, you should not compile it. Compilation gives you Func<Test, bool>, which will make your Where call use IEnumerable.Where, not IQueryable.Where.

var expression = Expression.Lambda<Func<Test, bool>>
    (Expression.Equal(propertyReference, constantReference),
    new[] { pe1 });

var resultUsingDynamicLinq = queryableTestData.Where(expression).ToList();

Upvotes: 2

Related Questions