Thursday, December 5, 2013

Expression Tree sample to build Dynamic queries to query List<> with Where condition in C#

Here is a sample program to build Dynamic queries to query List<> with Where condition
C# Code:

static void Main(string[] args)
{
    IQueryable<Country> queryableData = GetCountries().AsQueryable();
    ParameterExpression pe = Expression.Parameter(typeof(Country));
    MemberExpression me = Expression.PropertyOrField(pe, "Id");
    ConstantExpression cex = Expression.Constant(10, typeof(int));
    BinaryExpression be = Expression.LessThan(me, cex);
    MethodCallExpression whereCallExpression = Expression.Call(
  typeof(Queryable),
  "Where",
          new Type[] { queryableData.ElementType },
          queryableData.Expression,
          Expression.Lambda<Func<Country, bool>>(be, pe));
   IQueryable<Country> results = queryableData.Provider.CreateQuery<Country>(whereCallExpression);
    foreach (var item in results)
    {
        Console.Write(item.Id);
        Console.Write(" : ");
        Console.WriteLine(item.Name);
    }
    Console.ReadLine();
}

public static List<Country> GetCountries()
{
    // To get the country list in c# check my previous post Click Here 
    // i have added a Id property to the above link sample to make some condition work in this post
}

class Country
{
    public Int32 Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

Reference: MSDN

No comments:

Post a Comment