Search code examples
c#mathdata-structuressetset-theory

How to represent Empty Set?


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?


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));