Last active
August 27, 2023 16:16
-
-
Save santisq/3f43744b50c179ddd49d4ec9399918d5 to your computer and use it in GitHub Desktop.
implementation of IStructuralEquatable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Collections | |
class PSCustomObjectEquatable : IEquatable[object] { | |
hidden [object[]] $Properties | |
hidden [object[]] $Values | |
[object] $Instance | |
PSCustomObjectEquatable([object] $Instance) { | |
$psProperties = $Instance.PSObject.Properties | |
$this.Instance = $Instance | |
$this.Properties = @($psProperties.Name) | |
$this.Values = @($psProperties.Value) | |
} | |
[bool] Equals([object] $Other) { | |
return [PSCustomObjectEquatable]::Equals($this, [PSCustomObjectEquatable] $Other) | |
} | |
hidden static [bool] Equals( | |
[PSCustomObjectEquatable] $LHS, | |
[PSCustomObjectEquatable] $RHS | |
) { | |
if(-not $LHS.Properties.Count.Equals($RHS.Properties.Count)) { | |
return $false | |
} | |
if(-not $LHS.Values.Count.Equals($RHS.Values.Count)) { | |
return $false | |
} | |
$Comparer = [StructuralComparisons]::StructuralEqualityComparer | |
return $Comparer.Equals($LHS.Properties, $RHS.Properties) -and | |
$Comparer.Equals($LHS.Values, $RHS.Values) | |
} | |
[int] GetHashCode() { | |
$comparer = [StructuralComparisons]::StructuralEqualityComparer | |
return ([IStructuralEquatable] $this.Properties).GetHashCode($comparer) -bxor | |
([IStructuralEquatable] $this.Values).GetHashCode($comparer) | |
} | |
} | |
$hash = [System.Collections.Generic.HashSet[PSCustomObjectEquatable]]::new() | |
$hash.Add([PSCustomObjectEquatable] [pscustomobject]@{ foo = 'hello'; bar = 'World'; baz = 123 }) # true | |
$hash.Add([PSCustomObjectEquatable] [pscustomobject]@{ foo = 'hello'; bar = 'World'; baz = 123 }) # false | |
$hash.Add([PSCustomObjectEquatable] [pscustomobject]@{ foo = 'HELLO'; bar = 'World'; baz = 123 }) # true | |
[PSCustomObjectEquatable] [pscustomobject]@{ foo = 'hello'; bar = 'World'; baz = 123 } -eq | |
[PSCustomObjectEquatable] [pscustomobject]@{ foo = 'HELLO'; bar = 'World'; baz = 123 } # false | |
[PSCustomObjectEquatable] [pscustomobject]@{ foo = 'hello'; bar = 'World'; baz = 123 } -eq | |
[PSCustomObjectEquatable] [pscustomobject]@{ foo = 'hello'; bar = 'World'; baz = 123 } # true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment