36

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

4 Answers 4

45

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

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

4 Comments

Technically, this combines two arrays. The array is of fixed size so a pure prepend is not possible.
Is that a comma before the "aa"?
@RonJohn Correct, that's a comma.
Interesting syntax. What does the comma do? (I'm not sure how to frame a specific-enough Google search to find out myself.)
28

This combines two arrays into one.

$list = @("aa") + $list

It's impossible to do a pure prepending into a PowerShell array, because PowerShell arrays are fixed length. Combining two arrays into one is a good approach.

1 Comment

I like this answer, it's readable, it's intention is pretty clear!
20

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:

C:\> $list = new-object 'System.Collections.Generic.List[string]'
C:\> $list.Add('a')
C:\> $list.Add('b')
C:\> $list.Insert(0,'aa')
C:\> $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[].

2 Comments

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'
I am not sure why this answer isn't voted up enough times. For things like log processing, this will win over simple concatenation.
1

If you happen to want to do this to an 'Object' array rather than a 'String', I found the following useful:

$List = $List | foreach {'aa' + $_}

Obviously, this would be relatively slow for a gigantic array.

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.