Mikko Viitala
Mikko Viitala

Reputation: 8404

Modifying Expression<Func<T, bool>>

I haven't worked with expressions that much so I can't say if my intention makes any sense at all. I have looked around the interwebs and SO to no avail.

Say I have a method like so

public async Task<T> GetFirstWhereAsync(Expression<Func<T, bool>> expression)
{
    // this would be a call to 3rd party dependency
    return await SomeDataProvider
        .Connection
        .Table<T>()
        .Where(expression)
        .FirstOrDefaultAsync();
}

And from my-other-code I could be calling this e.g.

private async Task<User> GetUser(Credentials credentials)
{
    return await SomeDataSource
        .GetFirstWhereAsync(u => u.UserName.Equals(credentials.UserName));
}

So I'd be receiving first User from my SomeDataProvider that matches the given expression.


My actual question is how would I go about modifying GetFirstWhereAsync so that it would apply some SecretSauce to any expression passed to it? I could do this in caller(s) but that would be ugly and not much fun.

So if I pass in expressions like

u => u.UserName.Equals(credentials.UserName);
p => p.productId == 1;

I'd like these to be modified to

u => u.UserName.Equals(SecretSauce.Apply(credentials.UserName));
p => p.productId == SecrectSauce.Apply(1);

Upvotes: 2

Views: 1550

Answers (1)

Niyoko
Niyoko

Reputation: 7662

You can modify the expression inside method, but it's a bit complicated and you will need to do it case-by-case basis.

Example below will deal with modification from x => x.Id == 1 to x => x.Id == SecretSauce.Apply(1)


Class

class User
{
    public int Id { get; set; }
    public string Name { get; set;}

    public override string ToString()
    {
        return $"{Id}: {Name}"; 
    }
}

Sauce

class SquareSauce
{
    public static int Apply(int input)
    {
        // square the number
        return input * input;
    }
}

Data

User[] user = new[]
{
    new User{Id = 1, Name = "One"},
    new User{Id = 4, Name = "Four"},
    new User{Id = 9, Name = "Nine"}
};

Method

User GetFirstWhere(Expression<Func<User, bool>> predicate)
{
    //get expression body
    var body = predicate.Body;

    //get if body is logical binary (a == b)
    if (body.NodeType == ExpressionType.Equal)
    {
        var b2 = ((BinaryExpression)body);
        var rightOp = b2.Right;

        // Sauce you want to apply
        var methInfo = typeof(SquareSauce).GetMethod("Apply");      

        // Apply sauce to the right operand
        var sauceExpr = Expression.Call(methInfo, rightOp);

        // reconstruct equals expression with right operand replaced 
        // with "sauced" one
        body = Expression.Equal(b2.Left, sauceExpr);

        // reconstruct lambda expression with new body
        predicate = Expression.Lambda<Func<User, bool>>(body, predicate.Parameters);
    }
    /*
        deals with more expression type here using else if
    */
    else
    {
        throw new ArgumentException("predicate invalid");
    }

    return user
        .AsQueryable()
        .Where(predicate)
        .FirstOrDefault();
}

Usage

Console.WriteLine(GetFirstWhere(x => x.Id == 2).ToString());

The method will turn x => x.Id == 2 to x => x.Id == SquareSauce.Apply(2) and will produce:

4: Four

Upvotes: 6

Related Questions