41

I always wondered why there's an equals keyword in linq joins rather than using the == operator.

Property deadline =
(from p in properties
 join w in widgets
    on p.WidgetID equals w.ID
 select p).First();

Instead of

Property deadline =
(from p in properties
 join w in widgets
    on p.WidgetID == w.ID
 select p).First();

[EDIT] Rephrased the question and revised the examples.

Michael Klement
  • 3,376
  • 3
  • 30
  • 34

2 Answers2

45

There's a nice explanation by Matt Warren at The Moth:

"The reason C# has the word ‘equals’ instead of the ‘==’ operator was to make it clear that the ‘on’ clause needs you to supply two separate expressions that are compared for equality not a single predicate expression. The from-join pattern maps to the Enumerable.Join() standard query operator that specifies two separate delegates that are used to compute values that can then be compared. It needs them as separate delegates in order to build a lookup table with one and probe into the lookup table with the other. A full query processor like SQL is free to examine a single predicate expression and choose how it is going to process it. Yet, to make LINQ operate similar to SQL would require that the join condition be always specified as an expression tree, a significant overhead for the simple in-memory object case."

However, this concerns join. I'm not sure equals should be used in your code example (does it even compile?).

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    You're right, it doesn't even compile, my bad! It's been some time since I had the issue with == and equals, but I guess it was with a join back then when I accidentally used ==. Thanks for the explanation, anyway! – Michael Klement Jul 14 '09 at 07:24
17

Your first version doesn't compile. You only use equals in joins, to make the separate halves of the equijoin clear to the compiler.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yeah, sorry, my bad. It's been some time since I had the issue (which of course was with a join), where I accidentally put == instead of equals and wondered why there is a equals keyword in the first place. I just remembered it as I did not find an answer to it ;) – Michael Klement Jul 14 '09 at 07:29
  • So in the join case, is it legitimate to use == or should you always use equals? – Stephen Holt Apr 14 '14 at 11:54
  • 3
    @StephenHolt: No, you always need to use `equals` when performing a `join` in a query expression. That's part of the syntax. – Jon Skeet Apr 14 '14 at 19:49
  • I know that it is an old post. But here `equals` means reference equal? I mean reference versus value equality? – Hello Oct 20 '20 at 13:49
  • @Hello: No, LINQ uses the default equality comparer for the type in joins (within query syntax; if you use method syntax you can specify an equality comparer). – Jon Skeet Oct 20 '20 at 14:10