繁体   English   中英

基于另一个阵列的阵列

[英]Resort one array based on another array

我正在寻找基于另一个阵列的阵列。 在以前的项目中,我只需要获取无序项目的列表,并将该代码应用到我当前的场景中,我就得到了

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

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

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

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

OverloadDefinitions
-------------------
int IList.IndexOf(System.Object value)

但是值得注意的是这种方法是区分大小写的 如果您希望使用不区分大小写的方法查找索引,可以使用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)

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

这两个选项都应在其Predicate<T>中使用不区分大小写的相等比较器 ( -eq / -ne )

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

[Collections.Generic.List[string]] $definedSet = 'powershell', 'is', 'awesome'
$history   = 'Awesome', 'PowerShell', 'set', 'not in', 'is'
$predicate = [Predicate[string]]{ param($i) $i -eq $_ }

$history | Sort-Object { $definedSet.FindIndex($predicate) }, { $_ }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM