PowerShell 中的集合(数据结构)

Set (data structure) in PowerShell

有没有办法在 PowerShell 中定义 Set data-structure?

In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. It is a computer implementation of the mathematical concept of a finite set. Unlike most other collection types, rather than retrieving a specific element from a set, one typically tests a value for membership in a set.

我需要使用一个数据结构作为密钥库:

您可以使用在 System.Collections.Generic:

下找到的 .NET HashSet class
$set = New-Object System.Collections.Generic.HashSet[int]

该集合保证唯一项,Add, Remove, and Contains 方法的平均复杂度为 O(1)。

如果您更喜欢使用本机 PowerShell 类型,可以使用 HashTable 并忽略键值:

# Initialize the set
$set = @{}

# Add an item
$set.Add("foo", $true)

# Or, if you prefer add/update semantics
$set["foo"] = $true

# Check if item exists
if ($set.Contains("foo"))
{
    echo "exists"
}

# Remove item
$set.Remove("foo")

有关详细信息,请参阅:https://powershellexplained.com/2016-11-06-powershell-hashtable-everything-you-wanted-to-know-about/#removing-and-clearing-keys

如果您只想将唯一值存储在数组中且添加、删除和查找操作相对较快,那么哈希集就是您要寻找的。它可以创建为 -

$set = [System.Collections.Generic.HashSet[int]]@()