PoshBytes: Arrays vs. Lists
What is the difference between Arrays and Lists, and SPOILER ALERT why you should use Lists.
This post is a companion for the video embedded below. Scroll down to see the code from the video.
Arrays: Creating and Appending
Arrays have a fixed size. Using += creates a new array each time.
$arr = 1,2,3
$arr
$arr += 4
$arr
Lists: Creating, Adding, and Editing In Place
Lists are dynamic. They support in-place add, insert, and remove operations.
$list = [Collections.Generic.List[string]]('alpha','beta','gamma')
$list
$list.Add('delta')
$list
$list.Insert(1,'between')
$list
$list.Remove('gamma')
$list
$list.RemoveAt(0)
$list
Indexing Helper Used In Examples
This helper function prints index and value for any collection that supports indexing and .Count.
Function Test-Array {
param (
$InputObject
)
for($i = 0; $i -lt $InputObject.Count; $i++) {
Write-Host "$i - $($InputObject[$i])"
}
}
Combining Collections: Arrays vs Lists
Start with two arrays
$a = 1,2,3
$b = 'A','B','C'
Combine using an Array accumulator
Each += creates a new array, then assigns it back.
$array = @()
$array += $a
$array += $b
Test-Array $array
Add arrays into a List using Add()
This produces a list of two elements where each element is an array.
$list = [Collections.Generic.List[object]]::new()
$list.Add($a)
$list.Add($b)
Test-Array $list
Flatten into a List using AddRange()
AddRange appends each element of the input arrays to the list.
$list = [Collections.Generic.List[object]]::new()
$list.AddRange($a)
$list.AddRange($b)
Test-Array $list
Key Points
- Arrays are fixed-size.
+=creates a new array each time. - Lists are dynamic. Use
.Add(),.Insert(),.Remove(),.RemoveAt(), and.AddRange(). - Use arrays for small, fixed data or when an API specifically expects an array.
- Use lists when you need frequent inserts and appends.
- Both arrays and lists support indexing and
.Count.