Skip to content

Commit f71f66f

Browse files
committed
Better README #2
1 parent 5863943 commit f71f66f

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

README.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ if (-not ($array | All { $_ -is [int] })) {
5353

5454
## Collection Constructors
5555

56-
These cmdlets provide easier ways of constructing the more nuanced, generic types within the <code>System.Collections.Generic</code> API namespace.
56+
These cmdlets provide easier ways of constructing the more nuanced, generic types within the `System.Collections.Generic` API namespace.
5757

5858
### New-List
5959

@@ -72,4 +72,45 @@ $list = @(1, 2, '3') | New-List [int]
7272
# -or-
7373
$list = New-List [int] -InputObject @(3, '100', 56)
7474
75+
```
76+
77+
### New-HashSet
78+
79+
Constructs and returns a list of type [`[System.Collections.Generic.HashSet[T]]`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1#remarks "See MS Docs about HashSet[T]") where `T` is the generic type defined through the `-GenericType` parameter (defaults to `[object]`).
80+
81+
This module makes utilizing a HashSet in PowerShell much easier through the use of "ScriptBlock equality comparers". With no pre-compiled or custom-defined `IEqualityComparer[T]` classes necessary, the `New-HashSet` cmdlet lets you define the equality comparison methods through normal PowerShell ScriptBlocks.
82+
83+
Let's say you are importing a CSV where many values of a specific column are duplicates and you only need the first one of each:
84+
85+
```csv
86+
"Id", "Name", "Job"
87+
"1", "John", "The Guy"
88+
"1", "John", "The Guy?"
89+
"2", "Jane", "[redacted]"
90+
```
91+
92+
Using data like this, we can create a custom HashSet where as long as both the `Id` and `Name` columns are the same, the __entire__ object should be treated as the same.
93+
94+
```powershell
95+
$csv = Import-Csv -Path .\Employees.csv
96+
97+
# The equality scriptblock must return a [bool] (true/false) value.
98+
$equality = { # $left and $right -or- $x and $y -- must be used.
99+
$left.Name -eq $right.Name -and $left.Id -eq $right.Id
100+
}
101+
# The hashcode scriptblock must return an [int] value.
102+
$hashCode = { # $_|$this|$psitem -- must be used.
103+
$name = $_ | Select -ExpandProperty Name | % ToUpper
104+
$id = ($_ | Select -ExpandProperty Id) -as [int]
105+
106+
[System.HashCode]::Combine($name, $id)
107+
}
108+
109+
$set = New-HashSet -EqualityScript $equality -HashCodeScript $hashCode -Capacity 2
110+
111+
$set.Add($csv[0])
112+
# Outputs 'true'
113+
114+
$set.Add($csv[1])
115+
# Outputs 'false' and is not added to the set.
75116
```

0 commit comments

Comments
 (0)