Reputation: 19
I was wondering if there was a better way I can grab a single row matching a specific query, without searching twice. In my code originally, I wanted to count how many rows in my .CSV matched my search query.
$raisins=($table | ? {$_.'fruit' -like '*grapes*' -and $_.'hours in sunlight' -like '*a lot*'}| measure).Count
Now, I'm tasked with taking a single row from those same search query results.
$raisinHit=($table | ? {$_.'fruit' -like '*grapes*' -and $_.'hours in sunlight' -like '*a lot*})
$raisinHit=$raisinHit[0]
However, I find it really inefficient that I have to search through my .CSV using the same query from earlier, just to find a single result I had already glossed over. Is there a better way to do this? If so, can you explain how?
Upvotes: 1
Views: 98
Reputation: 24343
Just assign the matches to a variable, then return the count and an element from the variable.
$raisins = @($table |
? {$_.'fruit' -like '*grapes*' -and $_.'hours in sunlight' -like '*a lot*'})
$raisins.count
$raisins[0]
The @()
around the pipeline ensures that $raisins
will be an array, even if only one match is returned.
Upvotes: 1