Linq:联接中==和equals有什么区别? [英] Linq: What is the difference between == and equals in a join?

查看:124
本文介绍了Linq:联接中==和equals有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道为什么linq联接中有一个equals关键字而不是使用==运算符.

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();

代替

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

改写了问题并修改了示例.

Rephrased the question and revised the examples.

推荐答案

Matt Warren在

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

" C#之所以使用单词等于"而不是"=="运算符,是为了清楚说明"on"子句需要您提供两个单独的表达式,这些表达式用于比较相等性而不是单个谓词表达式.从联接模式映射到Enumerable.Join()标准查询运算符,该运算符指定两个单独的委托,这些委托用于计算可以进行比较的值,需要将它们作为单独的委托,以使用一个和探针构建查找表像SQL这样的完整查询处理器可以自由地检查单个谓词表达式并选择如何处理它,但是要使LINQ类似于SQL进行操作,则需要始终指定连接条件作为一个表达式树,对于简单的内存对象情况来说,这是相当大的开销."

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

但是,这与join有关.我不确定您的代码示例中是否应使用equals(它甚至可以编译吗?).

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

这篇关于Linq:联接中==和equals有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆