Dynamic Linq Coalesce

c# dynamic-linq linq

Question

I am using Dynamic Linq to query our database with a string that is created based on the filters a user enters. In one case, we need to perform a coalesce on two fields in order to apply our filter to the result.

The resulting syntax would look something like this:

(nullableField ?? requiredField) == "foo"

Or, if using an extension method:

(nullableField ?? requiredField).Contains("foo")

Dynamic Linq, or at least to version we currently have in our project, doesn't support coalesce, are there any implementations available or suggestions as to how I can implement my own? I have little experience with expressions and I'm struggling to create my own. So far, the following code works on my limited testing but I'm not sure if I have done it correctly.

This is called by ParseExpression():

    // ?? operator
    Expression ParseCoalesce()
    {
        Expression left = ParseLogicalOr();
        if (token.id == TokenId.DoubleQuestion)
        {
            NextToken();
            Expression expr1 = ParseExpression();
            left = Expression.Coalesce(left, expr1);
        }
        return left;
    }

Thoughts on this code? Is there a better way to do it?

1
2
2/29/2012 3:33:20 PM

Accepted Answer

If your system supports ConditionalExpression, you could implement it like

(nullableField != null ? nullableField == "foo" : requiredField == "foo")

or

(nullableField != null ? nullableField : requiredField) == "foo"
1
2/29/2012 4:00:39 PM

Popular Answer

Reviving this question from the dead since it appears to be the only one related to the coallesce operator in dynamic linq. The version I've been building off of handles the ternary operator in ParseExpression, so I just extended that, similar to how you went about doing it:

    Expression ParseExpression()
    {
        int errorPos = token.pos;
        Expression expr = ParseLogicalOr();
        if (token.id == TokenId.Coalesce)
        {
            NextToken();
            Expression expr1 = ParseExpression();
            expr = Expression.Coalesce(expr, expr1);
        }
        else if (token.id == TokenId.Question)
        {
            NextToken();
            Expression expr1 = ParseExpression();
            ValidateToken(TokenId.Colon, Res.ColonExpected);
            NextToken();
            Expression expr2 = ParseExpression();
            expr = GenerateConditional(expr, expr1, expr2, errorPos);
        }
        return expr;
    }

As I've run into missing functionality (thenby, in, etc), I've been adding it to a custom library located here:

https://github.com/jayoungers/DynamicExpressions/tree/master/DynamicExpressions/Linq

It's available in NuGet as DynamicExpressions



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow