重载列表.排序
我有一个需要排序的 List(Of MyObject)
。因此,我确保实现了 IComparable
、IEquatable
、IEqualityComparer
和 IComparer
并且排序工作正常。
项目有了新的新要求。排序列表不能包含“重复”对象。这种情况下的重复与出于排序目的定义重复的方式略有不同。我创建了一个新例程,它将检查两个对象并返回首选对象。首选值是除一个值外所有值都相同且最后一个值最大的值。我已经让这个例程运作良好。
现在我很想通过创建一个继承 IList(Of MyObject)
的对象来解决这个“删除重复项”问题,然后重写 Sort
方法以首先删除“重复项”,然后然后使用 IComparable
接口进行排序,就像 List
通常会自行排序。但是,我不知道该怎么做。从我迄今为止读到的内容来看,这似乎是不可能的。我知道我可以通过创建一个单独的例程(例如 SortWithRemove
或类似的例程)来解决这个问题,但我想知道是否可以覆盖。
编辑:根据下面的建议,我决定不重写 Sort
而是使用扩展方法。这是我的代码:
Public Module Extensions
<System.Runtime.CompilerServices.Extension()> _
Public Sub SortRemovingDuplicates(list As List(Of UniCatalogEntry))
'filter out unwanted records
End Sub
End Module
I have a List(Of MyObject)
that I need to sort. So I've made sure to implement IComparable
, IEquatable
, IEqualityComparer
, and IComparer
and sorting works fine.
There is new a new requirement for the project. A sorted list can not contain 'duplicate' objects. Duplicate in this case is slightly different than how duplicate is defined for sorting purposes. I've created a new routine that will check two objects and return the preferred one. The preferred one is the one that has all values the same except for one and that last value is the biggest. I've gotten this routine working well.
Now I would love to solve this 'remove duplicates' issue by creating an object that inherits IList(Of MyObject)
and then overriding the Sort
method to first remove 'duplicates' and then to sort using the IComparable
interface as a List
would normally sort itself. However, I have no idea how to do this. It doesn't even seem possible from what I've read so far. I know I could solve this by just creating a separate routine like SortWithRemove
or something like that, but I was wondering if overriding is possible.
Edit: Based on the suggestions below I decided not to override Sort
but to use an extension method. Here is my code:
Public Module Extensions
<System.Runtime.CompilerServices.Extension()> _
Public Sub SortRemovingDuplicates(list As List(Of UniCatalogEntry))
'filter out unwanted records
End Sub
End Module
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要改变
List.Sort
的语义(我假设你的意思是这个,而不是IList.Sort
,它不存在)。如果这样做,你就违反了方法的契约。如果您需要在排序时删除重复项,请为此编写适当的新方法,例如
SortWithoutDuplicates
。您的目标违反了里氏替换原则。Don’t change the semantics of
List.Sort
(I’m assuming you mean that, notIList.Sort
, which doesn’t exist). You are breaking the method’s contract if you do.If you need to remove duplicates when sorting, then write an appropriate new method for this, e.g.
SortWithoutDuplicates
. What you aim to do breaks the Liskov substitution principle.创建一个扩展方法来处理排序和删除可能是有意义的重复。
It may make sense to create an Extension Method to handle sorting and removing the duplicates.