Find element in [Generic.List[Hashtable]] based on value of hash table key, then remove from list

Viewed 51

Given a [Generic.List[Hashtable]] of the following form

$list = [System.Collections.Generic.List[Hashtable]]::new()
$list.Add(@{
    id = 'one'
    data = 'first'
})
$list.Add(@{
    id = 'two'
    data = 'second'
})
$list.Add(@{
    id = 'three'
    data = 'third'
})

I can find a particular entry, say id='two', like this

$target = $list.Where({$_.id -eq 'two'})

However, I then need to delete this element. As far as I can tell the only way to delete is by index, and when I try to use the same predicate like so

$list.FindIndex({$_.id -eq 'two'})

I get back -1, I assume Not Found. I also tried

$list.FindIndex($target)

and that produces an error. Not a surprise since all the signatures expect a predicate of some sort.

Well, drat. Apparently I asked about finding indexes a few years ago, here. And while not mentioned specifically there, it would appear that the automatic variable $_ doesn't work here, but $args[0] does.

$list.RemoveAt($list.FindIndex({$args[0].id -eq 'two'}))
0 Answers
Related