我有一個包含 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?。?Occurrence
Value
- 1 回答
- 0 關注
- 123 瀏覽
添加回答
舉報
0/150
提交
取消