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?

4
  • 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. Commented Jun 21, 2019 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? Commented Jun 21, 2019 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? Commented Jun 21, 2019 at 14:19
  • The .NET framework doesn't contain a sortable collection that allows duplicate keys out of the box. You will have to use tricks if you need one. Commented Jun 21, 2019 at 14:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.