Thursday, December 5, 2013

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

Here is a Expression Tree sample to build Dynamic queries to query List<> with Sorting in C#
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.         MethodCallExpression orderByCallExpression = Expression.Call(
  7.               typeof(Queryable),
  8.               "OrderByDescending",
  9.               new Type[] { queryableData.ElementType, typeof(Int32) },
  10.               queryableData.Expression,
  11.               Expression.Lambda<Func<Country, Int32>>(me, pe));
  12.         IQueryable<Country> results = queryableData.Provider.CreateQuery<Country>(orderByCallExpression);
  13.         foreach (var item in results)
  14.         {
  15.             Console.Write(item.Id);
  16.             Console.Write(" : ");
  17.             Console.WriteLine(item.Name);
  18.         }
  19.         Console.ReadLine();
  20.     }

  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