User Principal Comparer (Service Class)
Custom comparer for DirectoryServices.AccountManagement.UserPrincipal objects based on their DistinguishedName property.
- Useful for removing duplicate users from lists by comparing their DistinguishedName.
- Compares DistinguishedName values case-insensitively.
VB
Public Class adUserPrincipalComparer
Implements IEqualityComparer(Of UserPrincipal)
''' <summary>
''' Determines whether two <see cref="UserPrincipal"/> instances are equal based on their DistinguishedName.
''' </summary>
''' <category>Service functions</category>
''' <param name="x">The first <see cref="UserPrincipal"/> to compare.</param>
''' <param name="y">The second <see cref="UserPrincipal"/> to compare.</param>
''' <returns>
''' <c>True</c> if both <see cref="UserPrincipal"/> objects have the same DistinguishedName (case-insensitive); otherwise, <c>False</c>.
''' </returns>
Public Overloads Function Equals(x As UserPrincipal, y As UserPrincipal) As Boolean Implements IEqualityComparer(Of UserPrincipal).Equals
If x Is Nothing OrElse y Is Nothing Then
Return False
End If
Return String.Equals(x.DistinguishedName, y.DistinguishedName, StringComparison.OrdinalIgnoreCase)
End Function
''' <summary>
''' Returns a hash code for the specified <see cref="UserPrincipal"/> based on the DistinguishedName.
''' </summary>
''' <category>Service functions</category>
''' <param name="obj">The <see cref="UserPrincipal"/> object.</param>
''' <returns>
''' A hash code based on the DistinguishedName if present; otherwise, <c>0</c>.
''' </returns>
Public Overloads Function GetHashCode(obj As UserPrincipal) As Integer Implements IEqualityComparer(Of UserPrincipal).GetHashCode
Return If(obj.DistinguishedName IsNot Nothing, obj.DistinguishedName.ToLower().GetHashCode(), 0)
End Function
End Class