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]
如果您更喜欢使用本机 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")
如果您只想将唯一值存储在数组中且添加、删除和查找操作相对较快,那么哈希集就是您要寻找的。它可以创建为 -
$set = [System.Collections.Generic.HashSet[int]]@()
有没有办法在 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
:
HashSet
class
$set = New-Object System.Collections.Generic.HashSet[int]
如果您更喜欢使用本机 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")
如果您只想将唯一值存储在数组中且添加、删除和查找操作相对较快,那么哈希集就是您要寻找的。它可以创建为 -
$set = [System.Collections.Generic.HashSet[int]]@()