C# Linq:连接中的 == 和 equals 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1123888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:45:47  来源:igfitidea点击:

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

c#linqjoinequals

提问by Michael Klement

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

我一直想知道为什么equalslinq 连接中有一个关键字而不是使用 == 运算符。

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.

[编辑] 重新表述问题并修改示例。

采纳答案by Konrad Rudolph

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

The Moth 的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."

“C# 使用‘equals’这个词而不是‘==’运算符的原因是为了明确‘on’子句需要你提供两个单独的表达式来比较相等性,而不是单个谓词表达式。来自- join 模式映射到 Enumerable.Join() 标准查询运算符,该运算符指定两个单独的委托,用于计算然后可以比较的值。它需要它们作为单独的委托,以便使用一个构建查找表并探索查找一个完整的查询处理器,如 SQL 可以自由地检查单个谓词表达式并选择它将如何处理它。然而,要使 LINQ 操作类似于 SQL 需要始终将连接条件指定为表达式树,对于简单的内存对象情况来说是一个很大的开销。”

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

然而,这令人担忧join。我不确定是否equals应该在您的代码示例中使用(它甚至可以编译吗?)。

回答by Jon Skeet

Your first version doesn't compile. You onlyuse equalsin joins, to make the separate halves of the equijoin clear to the compiler.

您的第一个版本无法编译。您使用equalsin 连接,以使编译器清楚等连接的单独部分。