tags:

views:

83

answers:

2

The Powershell code:

$list += "aa"

appends the element "aa" to the list $list. Is there a way to prepend an element? This is my solution, but there must be a way to do this in a single line.

$tmp = ,"aa";
$tmp += $list
$list = $tmp
+1  A: 

Using += and + on arrays in PowerShell is making a copy of the array every time you use it. That is fine unless the list/array is really large. In that case, consider using a generic list:

$list = new-object 'System.Collections.Generic.List[string]'
$list.Add('a')
$list.Add('b')
$list.Insert(0,'aa')
$list
aa
a
b

Note that in this scenario you need to use the Add/Insert methods. If you fall back to using +=, it will copy the generic list back to an object[].

Keith Hill
Note, your first $list will return an array of 2 elements. First element is 'aa', and second element is a nested list of 2 elements, 'a' and 'b'
Nestor
Doh! OK, removed that part.
Keith Hill
+2  A: 

In your example above, you should just be able to do:

$list = ,"aa" + $list

That will simply prepend "aa" to the list and make it the 0th element. Verify by getting $list[0].

nithins