Why does PowerShell flatten arrays automatically?

前端 未结 3 1690
遇见更好的自我
遇见更好的自我 2021-01-18 13:32

I\'ve written some pwsh code

\"a:b;c:d;e:f\".Split(\";\") | ForEach-Object { $_.Split(\":\") }
# => @(a, b, c, d,          


        
3条回答
  •  囚心锁ツ
    2021-01-18 14:12

    You can alternatively create also a stack or a queue. Below, I created with your array a stack.

    $array = "a:b;c:d;e:f".Split(";")
    $stack = New-Object -TypeName System.Collections.Stack
    $array | ForEach-Object { $stack.Push($_.Split(":")) }
    

    From here, the most used methods are .Push() to insert new items to your stack, .Peek() to use the first item of the stack and .Pop(), to retrieve and then remove the first item.

    You mentioned that you wanted to create an array. This is also possible by using the ToArray() method.

    $stackArray = $stack.ToArray()
    $stackArray[2]
    > a
    > b
    

    To keep in mind, creating a stack will inverse the order to the items.

提交回复
热议问题