0

I have an existing HashSet with 6 items:{ Value: 3, Occurrence: 1 },{ Value: 1, Occurrence: 2 },{ Value: 4, Occurrence: 2 },{ Value: 5, Occurrence: 1 },{ Value: 2, Occurrence: 1 },{ Value: 6, Occurrence: 1 }

Element class:

internal class Element
{
    public Element(int value)
    {
         this.Value = value;
          this.Occurrence = 1;
    }

    public int Value { get; set; }

    public int Occurrence { get; set; }
}

How I want to create a SortedSet from items of this hash set like this:

var sortedSet = new SortedSet<Element>(hashSet.AsEnumerable(), new SortedSetComparer());

SortedSetComparer:

 internal class SortedSetComparer : IComparer<Element>
 {
     public int Compare(Element x, Element y)
     {
         if (x != null && y != null)
         {
            if (x.Occurrence > y.Occurrence)
            {
                return 1;
            }
            if (y.Occurrence > x.Occurrence)
            {
                return -1;
            }

            return 0;
        }

        return 0;
    }
}

But in debug I see that only 2 first elements got into sorted set: {Value: 3, Occurrence: 1} and {Value: 1, Occurrence: 2}

What am I doing wrong?

Dortimer
  • 583
  • 6
  • 22
SimonD
  • 1,225
  • 2
  • 14
  • 24
  • 2
    You are not comparing the `Value` is your main issue. You are effectively saying `{ Value: 1, Occurrence: 2 }` and `{ Value: 4, Occurrence: 2 }` are the same **because that is what 0 signifies**. – mjwills Jun 21 '19 at 14:12
  • I want them to be sorted by Occurrence not Value. Anyway shouldn't they all go to sorted set regardless of underlying comparer? – SimonD Jun 21 '19 at 14:15
  • 1
    'A set has no duplicates' - I didn't know that, my fault.. Could you post your answer and I'll accept it? – SimonD Jun 21 '19 at 14:19
  • The .NET framework doesn't contain [a sortable collection that allows duplicate keys](https://stackoverflow.com/questions/5716423/c-sharp-sortable-collection-which-allows-duplicate-keys) out of the box. You will have to use tricks if you need one. – Theodor Zoulias Jun 21 '19 at 14:47

1 Answers1

2

As per the docs (and by definition):

Duplicate elements are not allowed.

Since in your comparison method you are returning 0 if two objects have the same Occurrence (but different Value), then the set believes those two objects are equal. The net effect - it adds the first item for each Occurrence value and ignores the rest.

To solve this issue, your comparison must compare Occurrence and then compare Value as well. 0 should be returned only if both Occurrence and Value are equal.

mjwills
  • 21,750
  • 6
  • 36
  • 59