简体   繁体   English

基于另一个阵列的阵列

[英]Resort one array based on another array

I am looking to resort one array based on another array.我正在寻找基于另一个阵列的阵列。 In a previous project I needed to just get a list of the disordered items, and applying that code to my current scenario I get this在以前的项目中,我只需要获取无序项目的列表,并将该代码应用到我当前的场景中,我就得到了

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

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

Which does indeed give me a list of all four items, because they are all out of order.这确实给了我所有四个项目的清单,因为它们都乱了套。 However, in this new scenario I need to resort $history based on $definedSet .但是,在这个新场景中,我需要基于$definedSet诉诸$history The key being that there could be items in one that aren't in the other.关键是其中可能有一些项目不在另一个中。 But I am starting with a simpler problem, and that has me stumped.但我从一个更简单的问题开始,这让我很困惑。 I feel certain [Linq.Enumerable] is the key, obviously, but my Google-Fu is not pointing me towards a solution.显然,我确信[Linq.Enumerable]是关键,但我的 Google-Fu 并没有为我指明解决方案。 I have tried the Microsoft Docs article on the Enumerable class, and my brain... melted.我已经尝试过有关 Enumerable 类的 Microsoft Docs 文章,我的大脑……融化了。

In this case you can sort by index , using Array.IndexOf :在这种情况下,您可以使用Array.IndexOf按索引排序

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

However it's worth noting this method is case-sensitive .但是值得注意的是这种方法是区分大小写的 If you wish to find indexes with a case-insensitive method you can use Array.FindIndex :如果您希望使用不区分大小写的方法查找索引,可以使用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)

Or you can initialize the set as a List<T> and use it's FindIndex(Predicate<T>) method .或者您可以将集合初始化为List<T>并使用它的FindIndex(Predicate<T>)方法

Both options should use a case-insensitive equality comparer ( -eq / -ne ) in their Predicate<T> .这两个选项都应在其Predicate<T>中使用不区分大小写的相等比较器 ( -eq / -ne )

Sort-Object allows you to sort by multiple expressions , in the example below it will sort first by the found index in the set and then alphabetically : 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