Dynamic Linq Query and Expression

c# dynamic-linq linq

Question

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();
    }
}
1
0
5/17/2014 4:54:27 AM

Accepted Answer

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();
2
5/17/2014 5:09:15 AM


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