Reputation:
Can someone explain why this doesn't work like I think it should.
double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.3, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };
IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);
foreach (double number in onlyInFirstSet)
Console.WriteLine(number);
/*
This code produces the following output:
2
2.1
2.3
2.4
2.5
*/
What I would expect is 2, 2.1, 2.3, 2.3, 2.3, 2.4, 2.5. Why would except return a distinct list? Is this a bug?
Update:
Ok, totally missed that point in the docs. Funny 4 people respond with the same answer. You would think you would just up vote the guy who answered it first.:)
Upvotes: 5
Views: 4330
Reputation: 311526
Why would except return a distinct list? Is this a bug?
Nope. Except
produces a set difference. See the documentation:
Produces the set difference of two sequences by using the default equality comparer to compare values.
To do what you want, just use Where
to filter the values appropriately. For example:
"abcdddefffg".Where(e => !"cde".Contains(e)); // Produces "abfffg".
Upvotes: 10
Reputation: 17427
Because "Except" is a "set" function, and the concept of a "set" is defined as a unique list of items. In other words, sets by definition cannot contain duplicates.
Upvotes: 1
Reputation: 147290
This is actually the correct behaviour. The Except
method is documented to return the set difference of the two IEnumerable arguments. Since by definition, sets cannot contain duplicate elements, these are eliminated in the result. See the MSDN docs for more info.
Upvotes: 1