tags:

views:

64

answers:

2

What is the difference between Equals and = in LINQ?

Dim list As List(Of Foo) = (From a As Foo In FooList _
Join b As Bar In BarList _
On a.Something = b.Something _
Select a).ToList()

versus

Dim list As List(Of Foo) = (From a As Foo In FooList _
Join b As Bar In BarList _
On a.Something Equals b.Something _
Select a).ToList()
+4  A: 

From The Moth who quoted Matt Warren

"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."

EDIT

Later in the article.

UPDATE: Vladimir Sadov from the Visual Basic team told me that VB also uses Equals for pretty much the same reasons.

Matthew Vines
This question was about VB.net, not C#
JaredPar
+1  A: 

The difference is that the second version will compile and the first one will not. The VB query syntax requires that the contextual keyword Equals be used when comparing items in a LINQ query in this fashion.

How this operator works is defined in section 11.21.5 of the VB language spec

  • Both expressions must be classified as a value.
  • Both expressions must reference at least one range variable.
  • The range variable declared in the join query operator must be referenced by one of the expressions, and that expression must not reference any other range variables.
  • If the types of the two expressions are not the exact same type, then
    • If the equality operator is defined for the two types, both expressions are implicitly convertible to it, and it is not Object, then convert both expressions to that type.
    • Otherwise, if there is a dominant type that both expressions can be implicitly converted to, then convert both expressions to that type.
    • Otherwise, a compile-time error occurs.
JaredPar