2

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?

1
  • As an side: $rows | Sort-Object outputs the results of the sort as a new array - Sort-Object never sorts in place; therefore: $rows = $rows | Sort-Object Commented Aug 11, 2020 at 20:44

1 Answer 1

3

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 ...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.