这似乎是一个非常愚蠢的问题,但我似乎无法弄明白。如何在对象的值之间建立关系?
我认为代码不言自明:
$Collection = ("Fruit","Banana"),("Vegetables","Aubergine"),("Fruit","Appel"),("Vegetables","Courgette") |
ForEach-Object {
[PSCustomObject]@{
'Type'=$_[0]
'Content'=$_[1]
}
}
if ($Collection.Type -contains "Fruit" -and $Collection.Content -contains "Courgette") {
Write-Host "We DID find a match" -ForegroundColor Green
}
else {
Write-Host "We didn't find a match" -ForegroundColor Red
}
<# Result
Fruit + Banana = "We DID find a match"
Fruit + Courgette= "We DID find a match"
#>
当这对配对匹配时,如何才能匹配?例如,我想在Fruit + Banana
的情况下匹配,但在Fruit + Courgette
的情况下不匹配。
对不起,如果这听起来很愚蠢......谢谢你的帮助。
答案 0 :(得分:2)
您不必创建新的自定义对象,PS已经提供了哈希表形状的键/值集合。你可以更简单:
$h = @{ "Banana" = "Fruit"; "Aubergine" = "Vegetables"; "Appel" = "Fruit" ; "Courgette" = "Vegetables"}
function CheckObject($k, $v){
if($h.Item($k) -eq $v){
Write-Host "We DID find a match";
}
else{
Write-Host "We did NOT find a match";
}
}
结果:
PS U:\> CheckObject "Banana" "Fruit"
We DID find a match
PS U:\> CheckObject "Banana" "Vegetables"
We did NOT find a match
PS U:\> CheckObject "Courgetee" "Vegetables"
We did NOT find a match
键(第一个值)必须是唯一的,因此从"Fruit","Banana"
翻转。
答案 1 :(得分:1)
您的收藏品具有唯一值(内容)和可重复的类型。在我的解决方案中,我假设你永远不会有重复的条目,例如&#34; Fruit / Banana&#34;和&#34;蔬菜/香蕉&#34;
您的逻辑测试是:$Collection.Type -contains "Fruit" -and $Collection.Content -contains "Courgette"
您的逻辑测试有什么问题? 您正在测试如果您的收藏品有&#34; Fruit&#34; (这是真的),如果您的收藏有&#34; Courguette&#34; (也是如此)。
如果你的收藏有&#34; Courgette&#34;你必须测试如果是的话,如果是那种&#34; Courguette&#34;对象是&#34; Fruit&#34; ...
您可以创建一个查找$ content的函数,如果存在则检查该类型。它应该在比赛中返回$ true。
function FindObject($type, $content)
{
$index = [array]::IndexOf($Collection.Content,$content)
if (($index -ge 0) -and ($Collection[$index].Type -eq $type))
{
return $true
}
else
{
return $false
}
}
编辑:正如 @Kayasax 发表评论,您可以使用以下方法保存代码
$Collection | ?{$_.Type -eq "Fruit" -and $_.Content -eq "Banana"}
而不是函数。 更少的代码行,但如果您想了解,则难以阅读和调试。
工作示例:
$Collection = ("Fruit","Banana"),("Vegetables","Aubergine"),("Fruit","Appel"),("Vegetables","Courgette") |
ForEach-Object {
[PSCustomObject]@{
'Type'=$_[0]
'Content'=$_[1]
}
}
function FindObject($type, $content)
{
$index = [array]::IndexOf($Collection.Content,$content)
if (($index -ge 0) -and ($Collection[$index].Type -eq $type))
{
return $true
}
else
{
return $false
}
}
#if ( $Collection | ?{$_.Type -eq "Fruit" -and $_.Content -eq "Courgette"} )
if ( (FindObject "Fruit" "Courgette") -eq $true)
{
Write-Host "We DID find a match" -ForegroundColor Green
}
else
{
Write-Host "We didn't find a match" -ForegroundColor Red
}