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:

    static void Main(string[] args)
    {
        IQueryable<Country> queryableData = GetCountries().AsQueryable();
        ParameterExpression pe = Expression.Parameter(typeof(Country));
        MemberExpression me = Expression.PropertyOrField(pe, "Id");
        MethodCallExpression orderByCallExpression = Expression.Call(
              typeof(Queryable),
              "OrderByDescending",
              new Type[] { queryableData.ElementType, typeof(Int32) },
              queryableData.Expression,
              Expression.Lambda<Func<Country, Int32>>(me, pe));
        IQueryable<Country> results = queryableData.Provider.CreateQuery<Country>(orderByCallExpression);
        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