As with the array, elements may be selected by index:
$list = New-Object System.Collections.Generic.List[String] $list.AddRange([String[]]("Tom", "Richard", "Harry")) $list[1] # Returns Richard
The generic list offers a variety of methods that may be used to find elements when the index is not known, such as the following:
$index = $list.FindIndex( { $args[0] -eq 'Richard' } )
In the preceding example, the ScriptBlock is a predicate. Arguments are passed into the ScriptBlock and all list items matching the query are returned.
The predicate is similar in syntax to Where-Object, except $args[0] is used to refer to the item in the list instead of the pipeline variable, $_.
A param block may be declared for the ScriptBlock to assign a more meaningful name to the argument ($args[0]) if desirable.
Alternatively, the IndexOf and LastIndex methods may be used. Both of these methods support additional arguments (as opposed to Array.IndexOf, which only supports a restrictive search for a value) to constrain the search. For example, the search may start at a specific index:
$list.IndexOf('Harry', 2) # Start at index 2 $list.IndexOf('Richard', 1, 2) # Start at index 1, and 2 elements
Finally, a generic list offers a BinarySearch (half-interval) search method. This method may dramatically cut the time to search very large, sorted, datasets when compared to a linear search.
In a binary search, the element in the middle of the list is selected, and compared to the value. If the value is larger, the first half of the list is discarded, and the element in the middle of the new, smaller, set is selected for comparison. This process repeats (always cutting the list in half) until the value is found (or it runs out of elements to test):
$list = New-Object System.Collections.Generic.List[Int] $list.AddRange([Int[]](1..100000000)) # Linear and Binary are roughly comparable Measure-Command { $list.IndexOf(24) } # A linear search Measure-Command { $list.BinarySearch(24) } # A binary search # Binary is more effective Measure-Command { $list.IndexOf(99767859) } # A linear search Measure-Command { $list.BinarySearch(99767859) } # A binary search
The time taken to execute a binary search remains fairly constant, regardless of the element position. The time taken to execute a linear search increases as every element must be read (in sequence).