Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting objects by multiple properties

Tags:

powershell

I'm trying to use PowerShell for sorting objects representing application verions

$versionsObjects = @{
    Major = 3
    Minor = 2
    Bugfix = 1
},
@{
    Major = 3
    Minor = 5
    Bugfix = 1
},
@{
    Major = 1
    Minor = 2
    Bugfix = 1
},
@{
    Major = 4
    Minor = 2
    Bugfix = 1
}

$sortedVersions = ($versionsObjects | Sort-Object -Property @{Expression="Major"; Descending=$true}, @{Expression="Minor" ;Descending=$true}, @{Expression="Bugfix"; Descending=$true})
$sortedVersions | %{echo ( "{0}.{1}.{2}" -f $_.Major, $_.Minor, $_.Bugfix)}

The output is in the same order as input:

3.2.1
3.5.1
1.2.1
4.2.1

But it should be

4.2.1
3.5.1
3.2.1
1.2.1

What am I doing wrong?

like image 391
Andrzej Gis Avatar asked Jul 23 '15 20:07

Andrzej Gis


People also ask

How do you sort an array of objects based on a property?

Example 1: Sort Array by Property NameThe sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.

Can we sort array of objects?

Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.


1 Answers

Your expressions aren't quite right. Try this for the Sort-Object part:

Sort-Object -Property @{Expression={$_.Major}; Descending=$true}, @{Expression={$_.Minor} ;Descending=$true}, @{Expression={$_.Bugfix}; Descending=$true})
like image 170
Mike Shepard Avatar answered Sep 29 '22 07:09

Mike Shepard