Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Enumerable.Except() only returns the same element once [duplicate]

Tags:

c#

linq

When running the code below, I would expect to see the number 3, two times, but apparently the Except() method only returns the same element once.

List<int> x = new List<int>() {1, 2, 3, 3};
List<int> y = new List<int>() { 1, 2 };

var z = x.Except(y); /* returns 3, only once  */

In the documentation they say that the set difference of two sets is defined as the members of the first set that do not appear in the second set. It is not documented that they return duplicate items only once. https://msdn.microsoft.com/en-us/library/bb300779(v=vs.110).aspx

Is this a bug, or do I miss something here?

The code of the Expect() method is available here: https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,e289e6c98881b2b8.

Shouldn't they do "if (!set.Contains(element)) yield return element;" instead of "if (set.Add(element)) yield return element;"?

like image 362
TWT Avatar asked Sep 10 '26 09:09

TWT


1 Answers

Apparently, this is not a bug; set difference here means that both sequences are treated as sets, consequently the result sequence contains each element only once. However, the documentation does not really enlarge on whether doubles can occur in the output or not.

like image 187
Codor Avatar answered Sep 12 '26 23:09

Codor