简体   繁体   中英

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:

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:

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:

Produces the set difference of two sequences by using the default equality comparer to compare values.

A Set is described as this:

A set is a collection of distinct objects, considered as an object in its own right

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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