Question

From set theory:

Sets A,B are disjoint exactly if A∩B = {}

where {} is empty set.

Reference: Elementary Set Theory with a Universal Set, by Randall Holmes

Furthermore it says;

It is not correct to say that disjoint sets A and B have “no intersection”; they do have an intersection, namely the empty set, but this intersection has no elements

Also if A and B are disjoint, then A∩B = B∩A = {}

In C#:

using System.Linq;
...
...

HashSet<string> a = new HashSet<string>(new[] { "a", "b" });
HashSet<string> b = new HashSet<string>(new[] { "d", "c" });

a.Intersect(b) == b.Intersect(a); // => false

Why?

If == is just comparing the Id of the object (instead; if a is b; not the is operator of C#), is there any way to represent actual Empty Set?

Was it helpful?

Solution

Your Intersect returns IEnumerable<string>. Therefore you are comparing two instances of IEnumerable. As L.B mentioned in the comments, you can use Any to check whether the resultant IEnumerable<string> is empty.

bool empty = !a.Intersect(b).Any();

Another way would be to use HashSet's SetEquals method.

var ab = new HashSet<string>(a.Intersect(b));

bool equal = ab.SetEquals(b.Intersect(a));

OTHER TIPS

The == operator in C# and most similar programming languages is not the kind of equality that you can find in mathematics. It behaves like that with most numbers, but even that is not always true (in case of floating point rounding errors). It is very different when it comes to comparing objects. In your case, it merely compares whether the two object instances are exactly the same or not (see Object.ReferenceEquals), and clearly they aren't the same. A new HashSet<string>() represents an empty set, but if you type it twice, they will be two different object instances. You can define your own custom equality operator if you like (see operator overloading).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top