简体   繁体   English

为什么Enumerable.Except返回DISTINCT项?

[英]why does Enumerable.Except returns DISTINCT items?

Having just spent over an hour debugging a bug in our code which in the end turned out to be something about the Enumerable.Except method which we didn't know about: 刚花了一个多小时调试我们代码中的错误,最后结果证明是我们不知道的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 }

or more generally: 或更一般地说:

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

Looking at the MSDN page: 查看MSDN页面:

This method returns those elements in first that do not appear in second. 此方法首先返回那些未出现在第二个元素中的元素。 It does not also return those elements in second that do not appear in first. 它也不会返回第二个中没有出现的元素。

I get it that in cases like this: 在以下情况下我得到它:

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

you get the empty array because every element in the first array 'appears' in the second and therefore should be removed. 你得到空数组,因为第一个数组中的每个元素'都出现'在第二个数组中,因此应该被删除。

But why do we only get distinct instances of all other items that do not appear in the second array? 但是为什么我们只得到第二个数组中没有出现的所有其他项的不同实例? What's the rationale behind this behaviour? 这种行为背后的理由是什么?

I certainly cannot say for sure why they decided to do it that way. 我当然不能肯定地说他们为什么决定这样做。 However, I'll give it a shot. 但是,我会试一试。

MSDN describes Except as this: MSDN描述除此之外:

Produces the set difference of two sequences by using the default equality comparer to compare values. 通过使用默认的相等比较器来比较值,生成两个序列的集合差异。

A Set is described as this: Set被描述为:

A set is a collection of distinct objects, considered as an object in its own right 集合是不同对象的集合,本身被视为对象

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

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