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?
If your system supports
ConditionalExpression, you could implement it likeor