0

I need to extend the Where method for IQueryable to something like this:

.WhereEx("SomeProperty", "==", "value")

I dont know if this is even possible, but i found this in SO : Unable to sort with property name in LINQ OrderBy

I tried this answer and it seems quite interesting (Ziad's answer):

using System.Linq;
using System.Linq.Expressions;
using System;

namespace SomeNameSpace
{
    public static class SomeExtensionClass
    {
        public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
        {
            var param = Expression.Parameter(typeof(T), "p");
            var prop = Expression.Property(param, SortField);
            var exp = Expression.Lambda(prop, param);
            string method = Ascending ? "OrderBy" : "OrderByDescending";
            Type[] types = new Type[] { q.ElementType, exp.Body.Type };
            var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
            return q.Provider.CreateQuery<T>(mce);
        }
    }
}

Is It possible to do the same with the Where method ?

Thanks.

Update :

I can now set an expression to pass to the Call method, but i get the following exception: "No generic method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic."

here is my code:

public static IQueryable<T> WhereEx<T>(this IQueryable<T> q, string Field, string Operator, string Value)
    {
        var param = Expression.Parameter(typeof(T), "p");
        var prop = Expression.Property(param, Field);

        var val = Expression.Constant(Value);
        var body = Expression.Equal(prop, val);

        var exp = Expression.Lambda<Func<T, bool>>(body, param);

        Type[] types = new Type[] { q.ElementType, typeof(bool) };

        var mce = Expression.Call(
                typeof(Queryable),
                "Where",
                types,
                exp
            );
        return q.Provider.CreateQuery<T>(mce);
    }

Notice that i dont use the Operator argument yet, instead i use Equal for debugging purpose.

Can someone help me with this please ?

Community
  • 1
  • 1
dafriskymonkey
  • 2,189
  • 6
  • 25
  • 48

1 Answers1

0

I did another post with a simplified question. the link is Here

    public static IQueryable<T> WhereEx<T>(this IQueryable<T> q, string Field, string Operator, string Value)
    {
        var param = Expression.Parameter(typeof(T), "p");
        var prop = Expression.Property(param, Field);

        var val = Expression.Constant(Value);
        var body = Expression.Equal(prop, val);

        var exp = Expression.Lambda<Func<T, bool>>(body, param);

        return System.Linq.Queryable.Where(q, exp);
    }
Community
  • 1
  • 1
dafriskymonkey
  • 2,189
  • 6
  • 25
  • 48