using equal and not equal in a linq join
LINQ only supports equality joins, there's not a way to use a different operator in the join
itself.
As you point out, you can just use a where
statement for the same effect. If you didn't have an equality comparison to join on, you can use multiple from
clauses.
From MSDN:
The
equals
operator
A join
clause performs an equijoin. In other words, you can only base matches on the equality of two keys. Other types of comparisons such as "greater than" or "not equals" are not supported. To make clear that all joins are equijoins, the join
clause uses the equals
keyword instead of the == operator. The equals
keyword can only be used in a join
clause and it differs from the == operator in one important way. With equals
, the left key consumes the outer source sequence, and the right key consumes the inner source. The outer source is only in scope on the left side of equals
and the inner source sequence is only in scope on the right side.
Non-Equijoins
You can perform non-equijoins, cross joins, and other custom join operations by using multiple from
clauses to introduce new sequences independently into a query. For more information, see How to: Perform Custom Join Operations (C# Programming Guide).
Not equal join could be achieved like,
var result = from Or in context.orders
join Usr in context.vw_AllUsers on
new { userid = Or.UserId, IsNotAnAdmin = true}
equals
new { userid = Usr.UserId, IsNotAnAdmin = (Usr.RoleName != "Admin") }
select ........
The sql equivalent for the above linq will have a case statement in the join condition.