Extension method returning lambda expression through compare
Asked Answered
G

3

9

I'm in the process of creating a more elaborate filtering system for this huge project of ours. One of the main predicates is being able to pass comparations through a string parameter. This expresses in the following form: ">50" or "5-10" or "<123.2"

What I have (as an example to illustrate)

ViewModel:

TotalCost (string) (value: "<50")
Required (string) (value: "5-10")

EF Model:

TotalCost (double)
Required(double)

Expression that I would like to use:

model => model.Where(field => field.TotalCost.Compare(viewModel.TotalCost) && field.Required.Compare(viewModel.Required));

Expression that I would like to receive:

model => model.Where(field => field.TotalCost < 50 && field.Required > 5 && field.Required < 10);

Or something akin to that

However... I have no idea where to start. I've narrowed it down to

public static Expression Compare<T>(this Expression<Func<T, bool>> value, string compare)

It may not be even correct, but this is about all I have. The comparison builder is not the issue, that's the easy bit. The hard part is actually returning the expression. I have never tried returning expressions as function values. So basically what I need to keep, is the field and return a comparison expression, pretty much.

Any help? :x

Update:

Alas this doesn't solve my problem. It may be because I have been up for the past 23 hours, but I have not the slightest clue on how to make it into an extension method. As I said, what I'd like... is basically a way to write:

var ex = new ExTest();
var items = ex.Repo.Items.Where(x => x.Cost.Compare("<50"));

The way I shaped out that function (probably completely wrong) is

public static Expression<Func<decimal, bool>> Compare(string arg)
{
    if (arg.Contains("<"))
        return d => d < int.Parse(arg);

    return d => d > int.Parse(arg);
}

It's missing the "this -something- value" to compare to in first place, and I haven't managed to figure out yet how to have it be able to get an expression input... as for ReSharper, it suggests me to convert it to boolean instead...

My head's full of fluff at the moment...

Update 2:

I managed to figure out a way to have a piece of code that works in a memory repository on a console application. I'm yet to try it with Entity Framework though.

public static bool Compare(this double val, string arg)
    {
        var arg2 = arg.Replace("<", "").Replace(">", "");
        if (arg.Contains("<"))
            return val < double.Parse(arg2);

        return val > double.Parse(arg2);
    }

However, I highly doubt that's what I'm after

Update 3:

Right, after sitting down and looking through lambda expressions again, before the last answer, I came up with something akin to the following, it doesn't fill in the exact requirements of "Compare()" but It's an 'overload-ish' Where method:

public static IQueryable<T> WhereExpression<T>(this IQueryable<T> queryable, Expression<Func<T, double>> predicate, string arg)
    {
        var lambda =
            Expression.Lambda<Func<T, bool>>(Expression.LessThan(predicate.Body, Expression.Constant(double.Parse(50.ToString()))));

        return queryable.Where(lambda);
    }

However, despite to my eyes, everything seeming logical, I get runtime exception of:

System.ArgumentException was unhandled
  Message=Incorrect number of parameters supplied for lambda declaration
  Source=System.Core
  StackTrace:
       at System.Linq.Expressions.Expression.ValidateLambdaArgs(Type delegateType, Expression& body, ReadOnlyCollection`1 parameters)
       at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, String name, Boolean tailCall, IEnumerable`1 parameters)
       at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, Boolean tailCall, IEnumerable`1 parameters)
       at System.Linq.Expressions.Expression.Lambda[TDelegate](Expression body, ParameterExpression[] parameters)

This being the culprit line obviously:

var lambda =
                Expression.Lambda<Func<T, bool>>(Expression.LessThan(predicate.Body, Expression.Constant(double.Parse(50.ToString()))));

I'm very close to the solution. If I can get that error off my back, I believe EF should be capable of translating that into SQL. Otherwise... well, the last response will probably go.

Gorky answered 15/5, 2012 at 11:33 Comment(2)
I think, that your update2 part won't execute against SQL Server (EF). Did you try it?Deluxe
Yep, just did. As I would have thought tbh.Gorky
D
7

To generate expression, that would be translated to SQL (eSQL) you should generate Expression manually. Here is example for GreaterThan filter creating, other filters can be made with similar technique.

static Expression<Func<T, bool>> CreateGreaterThanExpression<T>(Expression<Func<T, decimal>> fieldExtractor, decimal value)
{
    var xPar = Expression.Parameter(typeof(T), "x");
    var x = new ParameterRebinder(xPar);
    var getter = (MemberExpression)x.Visit(fieldExtractor.Body);
    var resultBody = Expression.GreaterThan(getter, Expression.Constant(value, typeof(decimal)));
    return Expression.Lambda<Func<T, bool>>(resultBody, xPar);
}

private sealed class ParameterRebinder : ExpressionVisitor
{
    private readonly ParameterExpression _parameter;

    public ParameterRebinder(ParameterExpression parameter)
    { this._parameter = parameter; }

    protected override Expression VisitParameter(ParameterExpression p)
    { return base.VisitParameter(this._parameter); }
}

Here is the example of usage. (Assume, that we have StackEntites EF context with entity set TestEnitities of TestEntity entities)

static void Main(string[] args)
{
    using (var ents = new StackEntities())
    {
        var filter = CreateGreaterThanExpression<TestEnitity>(x => x.SortProperty, 3);
        var items = ents.TestEnitities.Where(filter).ToArray();
    }
}

Update: For your creation of complex expression you may use code like this: (Assume have already made CreateLessThanExpression and CreateBetweenExpression functions)

static Expression<Func<T, bool>> CreateFilterFromString<T>(Expression<Func<T, decimal>> fieldExtractor, string text)
{
    var greaterOrLessRegex = new Regex(@"^\s*(?<sign>\>|\<)\s*(?<number>\d+(\.\d+){0,1})\s*$");
    var match = greaterOrLessRegex.Match(text);
    if (match.Success)
    {
        var number = decimal.Parse(match.Result("${number}"));
        var sign = match.Result("${sign}");
        switch (sign)
        {
            case ">":
                return CreateGreaterThanExpression(fieldExtractor, number);
            case "<":
                return CreateLessThanExpression(fieldExtractor, number);
            default:
                throw new Exception("Bad Sign!");
        }
    }

    var betweenRegex = new Regex(@"^\s*(?<number1>\d+(\.\d+){0,1})\s*-\s*(?<number2>\d+(\.\d+){0,1})\s*$");
    match = betweenRegex.Match(text);
    if (match.Success)
    {
        var number1 = decimal.Parse(match.Result("${number1}"));
        var number2 = decimal.Parse(match.Result("${number2}"));
        return CreateBetweenExpression(fieldExtractor, number1, number2);
    }
    throw new Exception("Bad filter Format!");
}
Deluxe answered 15/5, 2012 at 18:5 Comment(8)
This seems more useful. I have updated original question again, with my own partial solution which... well, still doesn't quite function.Gorky
I have implemented the function now into the filtering method. There are a few issues with EF though, first off "getter" mustn't have (MemberExpression) cast in front of it. It'll just exception. Second, the number regex (which is the easiest thing to fix) is slightly off, it should be (?<number>\d+(\.\d*)?), the one in your post says it requires a ".<numbers>" here. It doesn't settle for a non-decimal value. But other than that (y)Gorky
About Regex: right you are. Updated answer with {0,1} quantifier (same as ?).Deluxe
And about MemberExpression - tried this code, worked like a charm. var filter = CreateFilterFromString<TestEnitity>(x => x.SortProperty, ">2"); Could you give an example, when exception is raised?Deluxe
The problem was thrown by Entity Framework, I believe. On a generic repository test it worked fine for me as well.Gorky
> On a generic repository test it worked fine for me as well So what the problem ) Use generic one )Deluxe
A "generic repository test" I meant one that isn't plugged into EF. As soon as I plugged it into EF, it threw an exception, so I guess it's EF's translation to SQL in someplace.Gorky
Could you give more info on how you use this code. I've tested on SQL-Express + EF it worked fine. Could you give more examples of code, that doesn't work?Deluxe
F
5

One of the at-first-glance-magical features of the C# compiler can do the hard work for you. You probably know you can do this:

Func<decimal, bool> totalCostIsUnder50 = d => d < 50m;

that is, use a lambda expression to assign a Func. But did you know you can also do this:

Expression<Func<decimal, bool>> totalCostIsUnder50Expression = d => d < 50m;

that is, use a lambda expression to assign an Expression that expresses a Func? It's pretty neat.

Given you say

The comparison builder is not the issue, that's the easy bit. The hard part is actually returning the expression

I'm assuming you can fill in the blanks here; suppose we pass in `"<50" to:

Expression<Func<decimal, bool>> TotalCostCheckerBuilder(string criterion)
{
    // Split criterion into operator and value

    // when operator is < do this:
    return d => d < value;

    // when operator is > do this:
    return d => d > value;

    // and so on
}

Finally, to compose your Expressions together with && (and still have an Expression), do this:

var andExpression = Expression.And(firstExpression, secondExpression);
Freak answered 15/5, 2012 at 12:6 Comment(1)
Not sure if it's even applicable to the situation. Updated original post with comments.Gorky
H
0

The hard part is actually returning the expression.

Translate strings into more structured constructions like enums and classes to define properties, operators and filters:

Enum Parameter
    TotalCost
    Required
End Enum

Enum Comparator
    Less
    More
    Equals
End Enum

Class Criterion
    Public ReadOnly Parameter As Parameter
    Public ReadOnly Comparator As Comparator
    Public ReadOnly Value As Double

    Public Sub New(Parameter As Parameter, Comparator As Comparator, Value As Double)
        Me.Parameter = Parameter
        Me.Comparator = Comparator
        Me.Value = Value
    End Sub
End Class

Then a function to create expression is defined:

Function CreateExpression(Criteria As IEnumerable(Of Criterion)) As Expression(Of Func(Of Field, Boolean))
    Dim FullExpression = PredicateBuilder.True(Of Field)()

    For Each Criterion In Criteria
        Dim Value = Criterion.Value

        Dim TotalCostExpressions As New Dictionary(Of Comparator, Expression(Of Func(Of Field, Boolean))) From {
            {Comparator.Less, Function(Field) Field.TotalCost < Value},
            {Comparator.More, Function(Field) Field.TotalCost > Value},
            {Comparator.Equals, Function(Field) Field.TotalCost = Value}
        }

        Dim RequiredExpressions As New Dictionary(Of Comparator, Expression(Of Func(Of Field, Boolean))) From {
            {Comparator.Less, Function(Field) Field.Required < Value},
            {Comparator.More, Function(Field) Field.Required > Value},
            {Comparator.Equals, Function(Field) Field.Required = Value}
        }

        Dim Expressions As New Dictionary(Of Parameter, IDictionary(Of Comparator, Expression(Of Func(Of Field, Boolean)))) From {
            {Parameter.TotalCost, TotalCostExpressions},
            {Parameter.Required, RequiredExpressions}}

        Dim Expression = Expressions(Criterion.Parameter)(Criterion.Comparator)

        FullExpression = Expression.And(Expression)
    Next

    Return FullExpression
End Function

PredicateBuilder taken here is needed to combine two expressions with AND operator.

Usage:

Function Usage() As Integer

    Dim Criteria = {
        New Criterion(Parameter.TotalCost, Comparator.Less, 50),
        New Criterion(Parameter.Required, Comparator.More, 5),
        New Criterion(Parameter.Required, Comparator.Less, 10)}

    Dim Expression = CreateExpression(Criteria)
End Function

It will create expression exactly like provided in an example

field => field.TotalCost < 50 && field.Required > 5 && field.Required < 10
Hesperides answered 28/1, 2016 at 21:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.