0

I have two SortedSets:

SortedSet<SortedSet<int>> sset1 = new SortedSet<SortedSet<int>>();
SortedSet<SortedSet<int>> sset2 = new SortedSet<SortedSet<int>>();

Later on I check I make a new Sorted set:

 SortedSet<int> newSset = MethodThatReturnsSortedSet();

Now I want to check if sset1 and sset2 contain newSset:

if (!sset1.Contains(newSset) && !sset2.Contains(newSset))  <--error on this line
   {
       sset1.Add(next);
       //some more code
   }

So the error I get is Argument Exception, "at least one of these objects must implement IComparable.

I have looked at other questions with the same problem, but in their case they want to compare their own classes. I am just checking if a certain item is in a Set. So yea..I have no idea how to solve this, any pointers?

Aelion
  • 379
  • 1
  • 5
  • 16

1 Answers1

0

You can't have a SortedSet of SortedSets unless you specify a custom comparer, because SortedSet does not implement IComparable in itself.

Whenever you use the type SortedSet<X>, the set is organized in increasing order based on X, so X must be IComparable<X> or just IComparable, or else the SortedSet<X> must be created with the constructor overload which allows you to give a custom object of type IComparer<X>.

Which of these two SortedSet<int> comes first:

{ 3, 8, 25, }

or:

{ 3, 7, 9, 58, 12345678, }

ADDITION: With no answer to the above, I assumed you wanted lexicographic comparison, which seems somewhat natural. I wrote this class:

class LexicographicComparer : Comparer<SortedSet<int>>
{
    public override int Compare(SortedSet<int> x, SortedSet<int> y)
    {
        if (x == null || y == null)
            return Default.Compare(x, y);

        int firstDifference = x.Zip(y, Comparer<int>.Default.Compare)
            .Where(n => n != 0).FirstOrDefault();
        if (firstDifference != 0)
            return firstDifference;

        return Comparer<int>.Default.Compare(x.Count, y.Count);
    }
}

That class inherits from Comparer<> class and implements IComparer<> interface because of that. You use it when you construct your "nested" SortedSet, for example:

LexicographicComparer lc = new LexicographicComparer();
SortedSet<SortedSet<int>> sset1 = new SortedSet<SortedSet<int>>(lc);
SortedSet<SortedSet<int>> sset2 = new SortedSet<SortedSet<int>>(lc);
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181