I need to sort a list with multilevel indexes
(@('1', '2', '3', '1.1.1', '1.99', '2.5', '5.5', "10") | Sort-Object) -join ", "
1, 1.1.1, 1.99, 10, 2, 2.5, 3, 5.5
I came up with such a solution, but it does not work with indexes above ten
(@('1', '2', '3', '1.1.1', '1.99', '2.5', '5.5', "10") | Sort-Object {
$chanks = $_.Split('.')
$sum = 0
for ($i = 0; $i -lt $chanks.Count; $i++) {
$sum += [int]$chanks[$i] / [math]::Pow(10, $i)
}
$sum
}) -join ", "
1, 1.1.1, 2, 2.5, 3, 5.5, 10, 1.99
Based on Lance U. Matthews comment to your question ... | Sort-Object { [int] $_.Split('.')[0] }, { [int] $_.Split('.')[1] }, { [int] $_.Split('.')[2] }
,
here is a way to do the same thing while not knowing the number of nested levels.
It is done by checking the max nesting level and storing it into a variable, then building dynamically an array of scriptblock to sort against.
$Arr = @('1', '2', '3', '1.1.1', '1.99', '2.5', '5.5', "10", '12.9.3.1.5', '176', '12.9.9', '2.1')
$MaxDots = ($Arr | % { $_.Split('.').count } | Measure-Object -Maximum).Maximum
$sbl = for ($i = 0; $i -lt $MaxDots; $i++) {
{ [int] $_.Split('.')[$i] }.GetNewClosure()
}
$Arr | Sort-Object $sbl
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With