问题
I want to get the minimum value in an array and then get the index of that item, in one step without writing my own loop (if I have to please let me know).
I know I can just do the$b = ($a | Measure -Minimum).Minimum
But then I have to do[array]::IndexOf($a, $b)
And while that is normally okay, I'm looking for a way to do it once because I'm running this MANY MANY times in a loop.
Thanks!
EDIT: One step meaning without looping through the array twice
回答1:
Personally, I might consider a different data structure. Maybe something sorted to begin with...
This code may work for your needs:
$myArray = 5,66,4,33,2,9,9,12
$index = 0
$minIndex = 0
$minValue = [int]::MaxValue
$myArray | % { if ($minValue -gt $_) {$minValue = $_; $minIndex = $index}; $index++ }
"MinIndex $minIndex = MinValue $minValue"
回答2:
its a problem of type, try like this:
$myArray = [int[]]5,66,4,33,2,9,9,12
$minvalue=[int]($myArray | measure -Minimum).Minimum
$myArray.IndexOf($minvalue)
来源:https://stackoverflow.com/questions/42033959/get-minimum-value-in-an-array-and-then-get-index