Comparing Numeric Lists

by Dec 4, 2017

Often a script needs to find out whether two lists are the same, or which elements are missing from a list. Instead of investing much programming work, you can resort to so-called HashSets. Have a look:

$set1 = New-Object System.Collections.Generic.HashSet[int32] (,[int[]]@(1,2,5,7,9,12))
$set2 = New-Object System.Collections.Generic.HashSet[int32] (,[int[]]@(1,2,5,12,111))

"Original Sets:"

# in both
$copy = New-Object 'System.Collections.Generic.HashSet[int32]' $set1
"In Both"

# combine
$copy = New-Object 'System.Collections.Generic.HashSet[int32]' $set1
"All Combined"

# exclusive
$copy = New-Object 'System.Collections.Generic.HashSet[int32]' $set1
"Exclusive in Set 1"

# exclusive either side
$copy = New-Object 'System.Collections.Generic.HashSet[int32]' $set1
"Exclusive in both (no duplicates)"

The example illustrates how you can set up two numeric lists to start with: $set1 and $set2.

To calculate how one list differs from another list, first create a working copy of a list, then apply one of the plenty comparison methods, and compare your working copy with another list.

The result can be found directly in your working copy. Here is the result from above code:

Original Sets:
1 2 5 7 9 12
1 2 5 12 111
In Both
1 2 5 12
All Combined
1 2 5 7 9 12 111
Exclusive in Set 1
7 9
Exclusive in both (no duplicates)
7 9 111

Twitter This Tip! ReTweet this Tip!