Skip to content

Instantly share code, notes, and snippets.

@flaf
Created June 16, 2019 21:11
Show Gist options
  • Save flaf/a7f0706b971bc36c88ad9356a1a697c3 to your computer and use it in GitHub Desktop.
Save flaf/a7f0706b971bc36c88ad9356a1a697c3 to your computer and use it in GitHub Desktop.
powershell-sort-array-of-objects
# pwsh
PowerShell 6.2.1
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/pscore6-docs
Type 'help' to get help.

PS /root/mnt> class A {                                        
>> 
>> 
>>     [string] $x
>> 
>>     A ([string] $x) {
>>         $this.x = $x
>>     }
>> 
>>     [Boolean] Equals([A] $other) {
>>         if ($this.x -eq $other.x) { return $true } else { return $false }
>>     }
>> 
>> }
>> 
>> 
An error occurred while creating the pipeline.
+ CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : RuntimeException
 
PS /root/mnt> $error[0].Exception.GetBaseException() | select *
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $error[0].Exception.GetBaseException() | select *
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
@flaf
Copy link
Author

flaf commented Jun 16, 2019

PS /root/mnt> class A {
>> 
>>     [string] $x
>> 
>>     A ([string] $x) {
>>         $this.x = $x
>>     }
>> 
>>     [Boolean] Equals($other) {
>>         if ($this.x -eq $other.x) { return $true } else { return $false }
>>     }
>> 
>> }
>> 
>> 
PS /root/mnt> $x1 = [A]::new('xxx'); $x2 = [A]::new('yyy'); $x3 = [A]::new('xxx'); $x4 = [A]::new('zzz')
PS /root/mnt> $a = @($x1, $x2, $x3, $x4)
PS /root/mnt> $a | ForEach-Object { Write-Host $_.x }
xxx
yyy
xxx
zzz
PS /root/mnt> $a_cleaned = @($a | select -Unique)
PS /root/mnt> $a_cleaned | ForEach-Object { Write-Host $_.x }
xxx
PS /root/mnt>

@HumanEquivalentUnit
Copy link

class A : System.IComparable {

    [string] $x

    A ([string] $x) {
        $this.x = $x
    }

    [int] CompareTo($other) {
        return $this.x.CompareTo($other.x)
    }

    [Boolean] Equals($other) {
        if ($this.x -eq $other.x) { return $true } else { return $false }
    }

}


$x1 = [A]::new('xxx'); $x2 = [A]::new('yyy'); $x3 = [A]::new('xxx'); $x4 = [A]::new('zzz')
$a = @($x1, $x2, $x3, $x4)
$a | ForEach-Object { Write-Host $_.x }
write-host "--"
$a_cleaned = @($a | select -Unique)                                                                                   
$a_cleaned | ForEach-Object { Write-Host $_.x }

@flaf
Copy link
Author

flaf commented Jun 16, 2019

It works via the CompareTo() method in the class and it seems that Equals() method is not used at all by select -Unique.

It works with Sort-Object -Unique too where duplicated objects are remove and the array is sorted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment