Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort multilevel list

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

like image 613
Алексей Семенов Avatar asked Oct 15 '25 03:10

Алексей Семенов


1 Answers

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
like image 147
Sage Pourpre Avatar answered Oct 18 '25 01:10

Sage Pourpre