简体   繁体   English

Enumerable.Ex两次的重载之间的区别?

[英]Difference between two overloads of Enumerable.Except?

I am trying to understand the difference between two overloads of Enumerable.Except method ie 我试图理解Enumerable.Except方法的两个重载之间的区别,即

  • Except(IEnumerable, IEnumerable) 除外(IEnumerable,IEnumerable)
  • Except(IEnumerable, IEnumerable, IEqualityComparer) 除外(IEnumerable,IEnumerable,IEqualityComparer)

Obviously, the first differnce is that the first overload uses the default equality comparer while the other uses an IEqualityComparer , but I can achieve the same result with first method, by implementing an IEquatable interface (as mentioned in the MSDN documentation of Except method), then why this second overload is needed? 显然,第一个区别是第一个重载使用默认的相等比较器,而另一个重载使用IEqualityComparer ,但是我可以通过实现IEquatable接口(如Except方法的MSDN文档中所述)来使用第一种方法实现相同的结果,那为什么需要第二次超载呢?

Two reasons: 两个原因:

  1. You can only implement IEquatable<T> for your own types... whereas you can specify an IEqualityComparer<T> for any type, whether you can modify it yourself or not. 您只能为自己的类型实现IEquatable<T> ...而您可以为任何类型指定IEqualityComparer<T> ,无论您是否可以自己对其进行修改。

  2. There may be multiple ways of comparing a type for equality, but implementing IEquatable<T> only allows you to express one of them. 比较类型是否相等的方法可能有多种,但是实现IEquatable<T>仅允许您表达其中一种。

A simple example of all of this would be strings - consider: 一个简单的例子就是字符串-考虑:

string[] x = { "A", "B", "C" };
string[] y = { "A", "c" };

var bc = x.Except(y);
var justB = x.Except(y, StringComparer.OrdinalIgnoreCase);

We might want both results in different circumstances, which means we couldn't handle both with IEquatable<T> ... and we can't change how string implements IEquatable<T> anyway. 我们可能希望在不同的情况下都使用这两个结果,这意味着我们无法使用IEquatable<T>处理这两个结果,而且IEquatable<T>我们都无法更改string实现IEquatable<T>的方式。 (You're not limited to StringComparer of course - you could write an equality comparer which just used the length of the string, for example.) (当然,您不限于StringComparer ,您可以编写一个相等比较器,例如,仅使用字符串的长度。)

This isn't specific to LINQ, either - it's generally the case for any API which deals in equality, eg HashSet<> , Dictionary<,> etc. 这也不是LINQ特有的-任何平等处理的API都是这种情况,例如HashSet<>Dictionary<,>等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM