我在下面的类中有三个数组列表。我想让它们保持独特。但是,如果数组列表中只有一项(字符串)并且您使用 select -unique (或任何其他方法来实现此目的),它将返回字符串而不是字符串列表。用 @() 包围它也不起作用,因为这会将其转换为数组而不是数组列表,而我无法向其中添加内容。
有什么仍然有效的建议吗?我之前尝试过 HashSets,但不知何故有一些可怕的经历。请参阅我之前的帖子.. Post on hashset issue
代码如下:
Class OrgUnit
{
[String]$name
$parents
$children
$members
OrgUnit($name){
$this.name = $name
$this.parents = New-Object System.Collections.ArrayList
$this.children = New-Object System.Collections.ArrayList
$this.members = New-Object System.Collections.ArrayList
}
addChild($child){
# > $null to supress output
$tmp = $this.children.Add($child)
$this.children = $this.children | select -Unique
}
addParent($parent){
# > $null to supress output
$tmp = $this.parents.Add($parent)
$this.parents = $this.parents | select -Unique
}
addMember($member){
# > $null to supress output
$tmp = $this.members.Add($member)
$this.members = $this.members | select -Unique
}
}
最佳答案
您要向数组中添加一个新项目,然后从中选择唯一的项目,并在每次添加成员时重新评估它。这是非常低效的,也许可以尝试以下方法:
if (-not $this.parents.Contains($parent)) {
$this.parents.Add($parent) | out-null
}
即使使用 out-null 抑制效率最低的输出,也会快得多。
关于powershell - 使 arraylist 上的 select -unique 返回 arraylist 而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58932348/