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?
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.