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:

  1. static void Main(string[] args)
  2. {
  3.     IQueryable<Country> queryableData = GetCountries().AsQueryable();
  4.     ParameterExpression pe = Expression.Parameter(typeof(Country));
  5.     MemberExpression me = Expression.PropertyOrField(pe, "Id");
  6.     ConstantExpression cex = Expression.Constant(10, typeof(int));
  7.     BinaryExpression be = Expression.LessThan(me, cex);
  8.     MethodCallExpression whereCallExpression = Expression.Call(
  9.   typeof(Queryable),
  10.   "Where",
  11.           new Type[] { queryableData.ElementType },
  12.           queryableData.Expression,
  13.           Expression.Lambda<Func<Country, bool>>(be, pe));
  14.    IQueryable<Country> results = queryableData.Provider.CreateQuery<Country>(whereCallExpression);
  15.     foreach (var item in results)
  16.     {
  17.         Console.Write(item.Id);
  18.         Console.Write(" : ");
  19.         Console.WriteLine(item.Name);
  20.     }
  21.     Console.ReadLine();
  22. }

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

  1. class Country
  2. {
  3.     public Int32 Id { get; set; }
  4.     public string Code { get; set; }
  5.     public string Name { get; set; }
  6. }

Reference: MSDN

No comments:

Post a Comment