亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從現有集合創建 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 關注
  • 123 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號