Search code examples
c#methodsreflectionexpressionany

Expression Call Any Method Reverse


I'm trying to write manually this linq sentence:

item => !item.Matches.Any(m => m.MarketPlace == "Amazon");

I know calling the Any method, but how do I do the reverse?

...
...
var anyCall = Expression.Call(typeof(Enumerable), "Any", new[] { modelType }, models, lambdaExp); 
return Expression.Lambda<Func<T, bool>>(anyCall, item);

this code sql outputs 'Exists'. How to sql outputs 'Not Exists' ?


Solution

  • In this context reverse makes me think of reordering. If you want to negate an expression you can do it like so:

    var trueExpression = Expression.Constant(true);
    var falseExpression = Expression.Not(trueExpression);
    

    In debug view falseExpression is !True.

    To answer your question:

    var noneCall = Expression.Not(Expression.Call(typeof(Enumerable), "Any", new[] { modelType }, models, lambdaExp)); 
    

    should do the trick.