我有一個包含 6 個項(xiàng)目的現(xiàn)有 HashSet:{值:3,出現(xiàn)次數(shù):1},{值:1,出現(xiàn)次數(shù):2},{值:4,出現(xiàn)次數(shù):2},{值:5,出現(xiàn)次數(shù):1},{值:2,出現(xiàn)次數(shù):1},{值:6,出現(xiàn)次數(shù):1}元素類:internal class Element{ public Element(int value) { this.Value = value; this.Occurrence = 1; } public int Value { get; set; } public int Occurrence { get; set; }}我想如何從這個哈希集的項(xiàng)目中創(chuàng)建一個 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; }}但在調(diào)試中,我看到只有 2 個第一個元素進(jìn)入排序集合:{Value: 3, Occurrence: 1} 和 {Value: 1, Occurrence: 2}我究竟做錯了什么?
1 回答

波斯汪
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個贊
根據(jù)文檔(根據(jù)定義):
不允許重復(fù)的元素。
因?yàn)樵谀愕谋容^方法中,如果兩個對象具有相同Occurrence
(但不同Value
),你將返回 0,那么集合認(rèn)為這兩個對象是相等的。凈效果 - 它為每個Occurrence
值添加第一項(xiàng)并忽略其余項(xiàng)。
要解決這個問題,你的比較Occurrence
?也得比較再比較Value
。僅當(dāng)和相等時才應(yīng)返回 0?。?Occurrence
Value
- 1 回答
- 0 關(guān)注
- 129 瀏覽
添加回答
舉報
0/150
提交
取消