USER_8675309
USER_8675309

Reputation: 893

VB.NET LINQ query Where with AndAlso and Or

In VB.NET, if I am doing a LINQ query that looks like this:

From a in entitity.name
Where a.id = id _
AndAlso a.date < currentDate _
AndAlso a.statusId = 1 Or a.statusId = 3
Select

On line 4, will the or clause evaluate to return all entities with a statusId of 3, or will it only return the entities that fit the other criteria and have a statusId of 1 or 3?

If that line were changed to

 AndAlso (a.statusId = 1 Or a.statusId = 3)

How would that change the expected results?

Upvotes: 0

Views: 6402

Answers (2)

Bruno
Bruno

Reputation: 4655

In VB.NET, conjunction (And, AndAlso) operators occur before inclusive disjunction (Or, OrElse) operators. See Operator Precedence in Visual Basic.

So as soon as a.statusId = 3 is true, it will return true.

And adding parenthesis

AndAlso (a.statusId = 1 Or a.statusId = 3)

will therefore change the behaviour

from:

return TRUE if (a.id = id AND a.date < currentDate AND a.statusId = 1) OR a.statusId = 3

to:

return TRUE if a.id = id AND a.date < currentDate AND (a.statusId = 1 OR a.statusId = 3)

Upvotes: 3

RianBattle
RianBattle

Reputation: 898

From a in entitity.name
Where a.id = id _
AndAlso a.date < currentDate _
AndAlso a.statusId = 1 Or a.statusId = 3
Select

is equivalent to having (notice the addition of parentheses below):

From a in entitity.name
Where (a.id = id _
AndAlso a.date < currentDate _
AndAlso a.statusId = 1) Or (a.statusId = 3)
Select

Which would return any results where the id matches, the date is less than currentDate, and the status is 1. It will also return ANY results where the statusId is 3.

Whereas having:

From a in entitity.name
Where a.id = id _
AndAlso a.date < currentDate _
AndAlso (a.statusId = 1 Or a.statusId = 3)
Select

Would then return any results where the id matches, the date is less than currentDate, and the status is 1 or 3.

This is the same type of behavior you would see in SQL, or even in general math. 1 + 2 * 3 does not yield the same result as (1 + 2) * 3. It changes the order of operations/the meaning of the statement completely (at least in this case).

Upvotes: 1

Related Questions