Linq: What is the difference between == and equals in a join?

我是研究僧i 提交于 2019-12-20 15:57:14

问题


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.


回答1:


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?).




回答2:


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



来源:https://stackoverflow.com/questions/1123888/linq-what-is-the-difference-between-and-equals-in-a-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!