为什么Enumerable.Except返回DISTINCT项?

the*_*onk 10 .net c# linq

刚花了一个多小时调试我们代码中的错误,最后结果证明是我们不知道的Enumerable.Except方法:

var ilist = new[] { 1, 1, 1, 1 };
var ilist2 = Enumerable.Empty<int>();
ilist.Except(ilist2); // returns { 1 } as opposed to { 1, 1, 1, 1 }
Run Code Online (Sandbox Code Playgroud)

或更一般地说:

var ilist3 = new[] { 1 };
var ilist4 = new[] { 1, 1, 2, 2, 3 };
ilist4.Except(ilist3); // returns { 2, 3 } as opposed to { 2, 2, 3 }
Run Code Online (Sandbox Code Playgroud)

查看MSDN页面:

此方法首先返回那些未出现在第二个元素中的元素.它也不会返回第二个中没有出现的元素.

在以下情况下我得到它:

var ilist = new[] { 1, 1, 1, 1 };
var ilist2 = new[] { 1 };
ilist.Except(ilist2); // returns an empty array
Run Code Online (Sandbox Code Playgroud)

你得到空数组,因为第一个数组中的每个元素'都出现'在第二个数组中,因此应该被删除.

但是为什么我们只得到第二个数组中没有出现的所有其他项的不同实例?这种行为背后的理由是什么?

Mik*_* M. 16

我当然不能肯定地说他们为什么决定这样做.但是,我会试一试.

MSDN描述除此之外:

通过使用默认的相等比较器来比较值,生成两个序列的集合差异.

被描述为这样的:

集合是不同 对象的集合,本身被视为对象

  • +1实现使用哈希集将问题从O(NxN)减少到O(N). (2认同)