从数组中返回具有最高值的对象 [英] Return object from array with highest value

查看:43
本文介绍了从数组中返回具有最高值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从属性具有最高值的数组中返回一个对象.目前我正在做以下事情

I want to return an object from an array who's property has the highest value. Currently I am doing the following

Get-VM | Sort-Object -Property ProvisionedSpaceGB | Select-Object -Last 1

这有效但效率低下.我不需要对整个数组进行排序,我只需要具有最大值的对象.理想情况下,我会使用类似

This works but is inefficient. I don't need the entire array sorted, I just need the object with largest value. Ideally I would use something like

Get-VM | Measure-Object -Property ProvisionedSpaceGB -Maximum

但这仅返回对象属性的值,而不是整个对象.有没有办法让测量对象返回基础对象?

but this only returns the value of the object property, not the entire object. Is there a way to have measure-object return the base object?

推荐答案

不是直接的.Measure-Object 旨在成为获取这些值的简单方法,而不是它们的输入对象.您可以从 Measure-Object 中获取最大值,然后与数组进行比较,但这需要几个步骤:

Not directly. Measure-Object is intended to be an easy way to grab such values, not their input objects. You could get the maximum from Measure-Object and then compare against the array, but it takes a few steps:

$array = Get-VM
$max = ($array | measure-object -Property ProvisionedSpaceGB -maximum).maximum
$array | ? { $_.ProvisionedSpaceGB -eq $max}

您也可以完全放弃 Measure-Object 并遍历集合,随时替换最大值和输出.

You could also forgo Measure-Object entirely and iterate through the set, replacing the maximum and output as you go.

$max = 0
$array | Foreach-Object 
{ 
    if($max -le $_.ProvisionedSpaceGB)
    { 
        $output = $_ 
        $max = $_.ProvisionedSpaceGB
    } 
}
$output

这有点脏,以便始终返回单个值.如果您要在可能有多个具有相同最大值的值(例如,使用 Get-ChildItem 时的文件大小长度)的情况下重用它,则需要稍作调整.在两个或多个对象具有相同 ProvisionedSpaceGB 值的情况下,它将用后者替换 $output.你可以很容易地将 $output 变成一个集合来解决这个问题.

This is a little dirtier so as to always return a single value. It would need a minor adjustment if you were to reuse it in a case where there may be multiple values that have the same maximum (filesize lengths when using Get-ChildItem, for example). It will replace $output with the latter iterate in a case where two or more objects have the same value for ProvisionedSpaceGB. You could turn $output into a collection easily enough to fix that.

我自己更喜欢前一种解决方案,但我想提供一种不同的方式来思考问题.

I prefer the former solution myself, but I wanted to offer a different way to think about the problem.

这篇关于从数组中返回具有最高值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆