如果我有两个信息数组。一个很大,另一个则小得多。
$lista ="1,2,3,4,5...etc for a lot "
$listb ="1,9,11" (Much smaller)
If ($listA -contains $listB){
Do stuff
}
这有意义并且有效吗?
在我看来,它并不总是有效,而且我在仔细检查它时遇到了麻烦。
最佳答案
Containment Operators非常适合您的用例,但是,您尝试将一个数组与另一个数组进行比较,这是行不通的,这些运算符可以帮助您识别< em>元素(标量、单个值)存在于数组中。
两对 ( -in
/-notin
) 和 ( -contains
/-notcontains
) 应该同样有效,唯一的区别是标量放置的位置,对于第一对,标量位于 操作的左侧,而对于后者,标量位于右侧。
取自文档,帮助我们对解释给出一些观点:
<Collection> -contains <Test-object>
<Collection> -notcontains <Test-object>
<Test-object> -in <Collection>
<Test-object> -notin <Collection>
对于您当前的代码,这需要一个循环,可能是在小数组上。 为什么?
These operators stop comparing as soon as they detect the first match, whereas the equality operators evaluate all input members. In a very large collection, these operators return quicker than the equality operators.
按照该逻辑,您可以循环遍历您的小数组并添加比较,这取决于您哪个对您来说更具可读性。您的代码可能如下所示:
$lista = 1,2,3,4,5,6,7,8,9,10
$listb = 2,4,6,8,10
foreach($item in $listb)
{
if($item -in $lista) {
$item
# Do something here
}
}
在某些用例中, HashSet<T>
非常有用,例如,如果我们想从 $lista
中获取唯一值(在本例中,我们希望不区分大小写,因此在其构造函数中使用 StringComparer.OrdinalIgnoreCase Property )并查看 $listb
中还包含哪些值。 ,在这种情况下我们可能想要使用 .Contains(..)
或 .IntersectWith(..)
或 .ExceptWith(..)
此类的方法而不是运算符。
$lista = 'A','x','y','z','a','B','b','C','c'
$listb = 'a','B','c'
$hashset = [System.Collections.Generic.HashSet[string]]::new(
[string[]]$lista,
[System.StringComparer]::OrdinalIgnoreCase
)
# To find the elements of `$listB` present in `$hashset`
foreach($item in $listb)
{
if($hashset.Contains($item)) {
$item
}
}
# The other way around, find the elements of `$hashset`
# present in `$listb`
$hashset.IntersectWith([string[]]$listb)
$hashset
# And the opposite, elements of `$hashset` NOT present in `$listb`
$hashset.ExceptWith([string[]]$listb)
$hashset
关于powershell - -Contains 什么时候不起作用和/或我应该使用其他东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71166367/