I have the following class:
public class Test
{
public string Text { get; set; }
public int Number { get; set; }
}
And I'm creating and Expression tree of type Expression<Func<Test, bool>>
on this class. When I do it like this:
Expression<Func<Test, bool>> predicate1 = x => x.Text.Length > 5 && x.Number > 0;
I get the following debug view:
.Lambda #Lambda1<System.Func`2[NHLinqTest.Test,System.Boolean]>(NHLinqTest.Test $x) {
($x.Text).Length > 5 && $x.Number > 0
}
note: there's a &&
for and-operation.
When I do it like this:
var y = Expression.Parameter(typeof(Test));
var predicate2 = Expression.And(
Expression.GreaterThan(
Expression.Property(Expression.Property(y, "Text"), "Length"),
Expression.Constant(5)),
Expression.GreaterThan(
Expression.Property(y, "Number"),
Expression.Constant(0)));
I get the following debug view:
($var1.Text).Length > 5 & $var1.Number > 0
Note: there's &
for and-operation. Why do I get &
in the second case? How to modify predicate2
to get &&
instead of &
?
Thanks in advance!
Because it is &
- i.e. bitwise / non-short-circuiting "and". For &&
you want Expression.AndAlso
.
See also Expression.Or
(|
) vs Expression.OrElse
(||
).
Also, note that Expression
!= C# - it is language independent, so you might also see some cases where you don't get back (visually) what you would expect from C#.
Compare Expression.And:
Creates a BinaryExpression that represents a bitwise AND operation.
and Expression.AndAlso:
Creates a BinaryExpression that represents a conditional AND operation that evaluates the second operand only if the first operand evaluates to true.
And then compare that to your knowledge of the &
and &&
operators.
The "&" operator and Expression.And represent a bitwise and. The "&&" operator and Expression.AndAlso represent a logical (and short-cutting) and operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With