Wednesday 11 February 2015

Dynamic sorting in Linq


Code Snippet for Dynamic orderBy in Linq

public static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> query, string attribute, SortDirection direction)
        {
            try
            {
                string orderMethodName = direction == SortDirection.Ascending ? "OrderBy" : "OrderByDescending";
                Type t = typeof(T);

                var param = Expression.Parameter(t);
                var property = t.GetProperty(attribute);

                return query.Provider.CreateQuery<T>(
                    Expression.Call(
                        typeof(Queryable),
                        orderMethodName,
                        new Type[] { t, property.PropertyType },
                        query.Expression,
                        Expression.Quote(
                            Expression.Lambda(
                                Expression.Property(param, property),
                                param))
                    ));
            }
            catch (Exception)
            {
                return query; // Return unsorted query
            }
        }


How to use :

  string sort = "Status"
   var status = DBContext.Status.Where(s => s.IsDeleted == false);
   SortDirection enumSort = sortDir.ToUpper() == "ASC" ? SortDirection.Ascending : SortDirection.Descending;
   status = status.OrderByDynamic(sort, enumSort).ToList();