Extension Method to extend OrderBy

Ever needed to pass in different fields to order by into Linq? This extension helper for OrderBy has you covered!

             
        public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty,
                          bool desc)
        {
            string command = desc ? "OrderByDescending" : "OrderBy";
            var type = typeof(TEntity);
            var property = type.GetProperty(orderByProperty);
            var parameter = Expression.Parameter(type, "p");
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExpression = Expression.Lambda(propertyAccess, parameter);
            var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
                                          source.Expression, Expression.Quote(orderByExpression));
            return source.Provider.CreateQuery<TEntity>(resultExpression);
        }
        
    

call like this...

             
            var model =
                db.Downloads
                .Where(r => SearchTerm == null && r.CompanyID == _companyID && r.Flag == false && r.HiRez == false || r.Name.Contains(SearchTerm) && r.CompanyID == _companyID && r.Flag == false && r.HiRez == false)
                .OrderBy(orderByName, orderByDirection)
                .Select(r => new DownloadListVeiwModel