开发者

Overload List.Sort

开发者 https://www.devze.com 2023-03-30 19:38 出处:网络
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.

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 pref开发者_如何学Goerred 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


Don’t change the semantics of List.Sort (I’m assuming you mean that, not IList.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.

public static class Extensions
{
    public static void SortAndRemoveDuplicates<T>(this IList<T> list) where T is IComparable
    {
        // add magic here...
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号