62

Is there a way the define a Set data-structure in PowerShell?

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.

I need to use a data structure as keystore that:

  • assures no-repetitions;
  • minimizes the computational effort in order to retrieve and remove an element.

3 Answers 3

76

You can use the .NET HashSet class that is found under System.Collections.Generic:

$set = New-Object System.Collections.Generic.HashSet[int]

The collection guarantees unique items and the Add, Remove, and Contains methods all operate with O(1) complexity on average.

Sign up to request clarification or add additional context in comments.

Comments

32

If you prefer to stick with native PowerShell types, you can use HashTable and just ignore the key values:

# 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")

For more information see: https://powershellexplained.com/2016-11-06-powershell-hashtable-everything-you-wanted-to-know-about/#removing-and-clearing-keys

4 Comments

At least with powershell core $set.Add("foo", $true) throws an exception if the key already exists. Therefore $set["foo"] = $true should be used instead, as it not only allows creating new keys but also to update existing ones.
@K.Frank that really depends on the behavior you're after - you might very well want that exception is certain scenarios. I will conceded that it's more consistent with the Remove behavior (which doesn't throw if the item doesn't exist), so I'll add it to my answer - thanks!
So HashTable and HashSet is similar in PowerShell: No duplicate keys?
@Timo PowerShell types are .NET types. Since they are similar in that regard (no duplicate keys) in .NET, this similarity is the same in PowerShell: learn.microsoft.com/en-us/dotnet/api/…
10

Hashset is what you are looking for if you want to store only unique values in an array with relatively faster add, remove and find operations. It can be created as -

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

1 Comment

Can shorten slightly by omitting the System namespace: $set = [Collections.Generic.HashSet[int]]@() .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.