Reputation: 159
I have an array of strings make like this "name: number" and I need to order it by number every time that I add another row to the array but the sorting doesn't work.
The idea is that every time that the function is called I create a new row and I add it to the text. Then, for each row in the text I add in front of the row the number and a '@'. Now the array is like this:
15@foo:15
2@bar:2
4@foobar:4
Now I'd like to order it by number and then remove the part that I added to sort.
Function Add($name, $number) {
$newRow = "$($name):$number`r`n"
$Script:text = $Script:text + $newRow
ForEach($row in $text.Split("`r`n")) {
if ($row.length -ne 0) {
$rows = $rows + $row.Split(":")[1] + "@" + $row + "`r`n"
}
}
$rows | Sort-Object
ForEach($row in $rows.Split("`r`n")) {
$newText = $newText + $row.Split("@")[1] + "`r`n"
}
$textBox.Text = $newText
}
It all works except the sorting.
Does anyone knows how to fix it?
Upvotes: 2
Views: 1655
Reputation: 437478
You can sort your input directly, by passing a script block ({ ... }
) to Sort-Object
that extracts the number from each input string ($_
) and sorts based on it:
PS> 'foo:15', 'bar:2', 'foobar:4' | Sort-Object { [int] ($_ -split ':')[-1] }
bar:2
foobar:4
foo:15
In your case, since the lines are part of a single, multi-line string you need to split the string into individual lines first, then sort them, then rejoin the sorted lines:
(
@'
foo:15
bar:2
foobar:4
'@ -split '\r?\n' | Sort-Object { [int] ($_ -split ':')[-1] }
) -join [Environment]::NewLine
The output looks the same as above, but in this case it isn't an array of sorted lines, but a single multi-line string containing the sorted lines.
Note: Sort-Object
outputs a new array, it doesn't sort in place. Therefore, to save the sorted array back to the same variable, you must use something like:
$rows = $rows | Sort-Object ...
Upvotes: 3