为了账号安全,请及时绑定邮箱和手机立即绑定

从现有集合创建 C# SortedSet

从现有集合创建 C# SortedSet

C#
弑天下 2023-04-29 15:32:59
我有一个包含 6 个项目的现有 HashSet:{值:3,出现次数:1},{值:1,出现次数:2},{值:4,出现次数:2},{值:5,出现次数:1},{值:2,出现次数:1},{值:6,出现次数:1}元素类: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());排序集比较器: 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}我究竟做错了什么?
查看完整描述

1 回答

?
波斯汪

TA贡献1811条经验 获得超4个赞

根据文档(根据定义):

不允许重复的元素。

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

要解决这个问题,你的比较Occurrence 也得比较再比较Value仅当和相等时才应返回 0 。 OccurrenceValue


查看完整回答
反对 回复 2023-04-29
  • 1 回答
  • 0 关注
  • 80 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信