我需要从多个来源创建一个不同的历史项目列表,其中最新的项目是保留的。我正在尝试类似的方法,但由于问题域的原因,检查结果是否准确并不简单。
Function GetUnique {
param( $source1, $source2, ...)
$items = $source1 + $source2 + ...;
$unique = $items | Sort-Object -Desc -Unique -Prop Timestamp;
# Does this contain the most recent items?
$unique;
}
我很惊讶没有 -Stable 开关来指示偏好。
注意:我知道即使排序是稳定的,我也会对唯一性算法做出假设。如果排序是稳定的,我可以相对轻松地编写自己的稳定的 Get-Unique commandlet,假设稳定的排序输入。但是,我真的不想实现 MergeSort。
最佳答案
因此,在放弃我的场景之后,我发现了一个简单的测试来表明排序实际上并不稳定,但以某种方式以稳定的方式反转了序列。请注意,我使用的测试集非常小,因此这些结果可能不确定,但可以重现。
function f ([String] $name, [int] $value) `
{
return New-Object PSObject -Property @{ Name=$name; Value=$value } |
select Name,Value;
};
$test = (f a 1),(f a 2),(f a 3),(f b 1),(f b 2);
"`n`$test;"
$test;
"`n`$test | sort name;"
$test | sort name;
"`n`$test | sort name -Desc;"
$test | sort name -Desc;
"`n`$test | sort name | sort name;"
$test | sort name | sort name;
"`n`$test | sort value | sort name;"
$test | sort value | sort name;
"`n`$test | sort value;"
$test | sort value;
结果如下:
$test;
Name Value
---- -----
a 1
a 2
a 3
b 1
b 2
$test | sort name;
a 3
a 2
a 1
b 2
b 1
$test | sort name -Desc;
b 1
b 2
a 1
a 2
a 3
$test | sort name | sort name;
a 1
a 2
a 3
b 1
b 2
$test | sort value | sort name;
a 2
a 1
a 3
b 1
b 2
$test | sort value;
b 1
a 1
b 2
a 2
a 3
我已向 PS 团队提交了有关此问题的建议:https://connect.microsoft.com/PowerShell/feedback/details/752455/provide-stable-switch-for-sort-object-cmdlet 。如果您同意,请点赞。
关于sorting - Powershell Sort-Object 是否使用稳定排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11346871/