从现有集合创建 C# SortedSet

Creating C# SortedSet from existing collection

我有一个包含 6 个项目的现有 HashSet:{值:3,出现次数:1},{值:1,出现次数:2},{值:4,出现次数:2},{值:5,出现次数: 1 },{ 值:2,出现次数:1 },{ 值:6,出现次数:1 }

元素class:

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

    public int Value { get; set; }

    public int Occurrence { get; set; }
}

我想如何从这个哈希集的项目创建一个 SortedSet,如下所示:

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

但在调试中我看到只有 2 个第一个元素进入排序集合:{Value: 3, Occurrence: 1} 和 {Value: 1, Occurrence: 2}

我做错了什么?

根据the docs (and by definition):

Duplicate elements are not allowed.

因为在你的比较方法中,如果两个对象具有相同的 Occurrence(但不同的 Value),你将返回 0,那么集合认为这两个对象是 equal。净效果 - 它为每个 Occurrence 值添加第一项并忽略其余项。

要解决此问题,您的比较必须比较 Occurrence ,然后 还要比较 Value。仅当 OccurrenceValue 相等时才应返回 0。