基于另一个数组对一个数组进行度假村

Gor*_*don 4 sorting powershell enumerable

我希望基于另一个数组来使用一个数组。在之前的项目中,我只需要获取无序项目的列表,然后将该代码应用到我当前的场景中,我得到了这个

$definedSet = @('C', 'B', 'D', 'A')
$history = @('A', 'B', 'C', 'D')

$disordered = $history.Where({-not [Linq.Enumerable]::SequenceEqual([string[]]$history, [string[]]$definedSet)})
$disordered
Run Code Online (Sandbox Code Playgroud)

这确实给了我所有四个项目的列表,因为它们都是乱序的。然而,在这个新场景中我需要诉诸$history基于$definedSet. 关键是其中一个中可能存在另一个中没有的项目。但我从一个更简单的问题开始,这让我很困惑。显然,我觉得确定[Linq.Enumerable]是关键,但我的 Google-Fu 并没有为我指明解决方案。我已经尝试过有关 Enumerable 类的 Microsoft Docs 文章,我的大脑...融化了。

San*_*zon 6

在这种情况下,您可以使用Array.IndexOf按索引排序

OverloadDefinitions
-------------------
int IList.IndexOf(System.Object value)
Run Code Online (Sandbox Code Playgroud)

但值得注意的是,此方法区分大小写如果您希望使用不区分大小写的方法查找索引,可以使用Array.FindIndex

OverloadDefinitions
-------------------
static int FindIndex[T](T[] array, System.Predicate[T] match)
static int FindIndex[T](T[] array, int startIndex, System.Predicate[T] match)
static int FindIndex[T](T[] array, int startIndex, int count, System.Predicate[T] match)
Run Code Online (Sandbox Code Playgroud)

或者您可以将集合初始化为 aList<T>并使用它的FindIndex(Predicate<T>)method

两个选项-eq-ne都应Predicate<T>.

Sort-Object允许您按多个表达式排序,在下面的示例中,它将首先按集合中找到的索引排序,然后按字母顺序排序

$definedSet = 'powershell', 'is', 'awesome'
$history = 'Awesome', 'PowerShell', 'set', 'not in', 'is'
$predicate = [Predicate[string]] { $args[0] -eq $_ }
$history | Sort-Object { [array]::FindIndex($definedSet, $predicate) }, { $_ }
Run Code Online (Sandbox Code Playgroud)