Skip to content

Instantly share code, notes, and snippets.

@Sinstraliz
Created January 8, 2016 14:07
Show Gist options
  • Save Sinstraliz/1c74ef794c65cb3742fe to your computer and use it in GitHub Desktop.
Save Sinstraliz/1c74ef794c65cb3742fe to your computer and use it in GitHub Desktop.

Revisions

  1. Sinstraliz created this gist Jan 8, 2016.
    52 changes: 52 additions & 0 deletions Filter And Sort Extentions
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    //x => x.fieldName.Contains(fieldValue)
    public static IQueryable<T> FilterByValue<T>(this IQueryable<T> q, string fieldName, string fieldValue)
    {
    try
    {
    var param = Expression.Parameter(typeof(T), "p");
    var prop = Expression.Property(param, fieldName);

    if (((PropertyInfo)prop.Member).PropertyType != typeof(string))
    return q;

    var methodContains = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    Expression e1 = Expression.Call(prop, methodContains, Expression.Constant(fieldValue));
    var exp = Expression.Lambda<Func<T, bool>>(e1, param);
    var mce = Expression.Call(typeof(Queryable), "Where", new Type[] { q.ElementType }, q.Expression, exp);

    return q.Provider.CreateQuery<T>(mce);
    }
    catch (Exception ex)
    {
    return q;
    }
    }

    public static IQueryable<T> FilterByValue<T>(this ObjectQuery<T> q, string fieldName, string fieldValue)
    {
    return FilterByValue<T>(q.AsQueryable<T>(), fieldName, fieldValue);
    }

    public static IQueryable<T> OrderByField<T>(this IQueryable<T> queryable, string sortField, bool ascending)
    {
    try
    {
    var param = Expression.Parameter(typeof(T), "p");
    var prop = Expression.Property(param, sortField);
    var exp = Expression.Lambda(prop, param);
    var method = ascending ? "OrderBy" : "OrderByDescending";
    var types = new Type[] { queryable.ElementType, exp.Body.Type };
    var mce = Expression.Call(typeof(Queryable), method, types, queryable.Expression, exp);

    return queryable.Provider.CreateQuery<T>(mce);
    }
    catch (Exception ex)
    {
    return queryable;
    }
    }

    public static IEnumerable<T> OrderByField<T>(this IEnumerable<T> enumerable, string sortField, bool ascending)
    {
    return OrderByField<T>(enumerable.AsQueryable<T>(), sortField, ascending);
    }