Add Distinction to Your Code: VB: Use a Distinct Expression: Listing 2

Add this module to your project, and you can use a Distinct extension that takes two lambda functions as arguments for the comparison of objects. This class and extension method makes it easy to do different Distinct comparisons on complex types.

Imports System.Runtime.CompilerServices
Imports System.Collections.Generic

Module ObjectQueryExtensions

    <Extension()> _
        Public Function Distinct(Of T)( _
        ByVal source As IEnumerable(Of T), _
        ByVal equalFunc As Func(Of T, T, Boolean), _
        ByVal hashFunc As Func(Of T, Int32) _
        ) As IEnumerable(Of T)

    Return source.Distinct( _
        New DistinctComparer(Of T)(equalFunc, hashFunc))

    End Function


    Public Class DistinctComparer(Of T)
        Implements IEqualityComparer(Of T)

      Private _equalFunc As Func(Of T, T, Boolean)
      Private _hashFunc As Func(Of T, Int32)


        Sub New( _
            ByVal equalFunc As Func(Of T, T, Boolean), _


            ByVal hashFunc As Func(Of T, Int32))

            _equalFunc = equalFunc
            _hashFunc = hashFunc
        End Sub


        Public Function IEqualityComparer_Equals( _
            ByVal x As T, _
            ByVal y As T _
            ) As Boolean _
            Implements IEqualityComparer(Of T).Equals
            Return _equalFunc(x, y)
        End Function


        Public Function IEqualityComparer_GetHashCode( _
            ByVal obj As T _
            ) As Int32 _
            Implements IEqualityComparer( _ 		     Of T).GetHashCode
            Return _hashFunc(obj)
        End Function

    End Class

End Module
comments powered by Disqus

Featured

Subscribe on YouTube