Powershell: add new member to array "union" and "difference"

Created on 8 Jan 2020  路  3Comments  路  Source: PowerShell/PowerShell

compare-object and get-unique is awsome but its more easy to add method like union and difference in array

step to reproduce

PS> $a = 1, 1, 2, 3
PS> $b = 3, 4

PS> $a.union($b) 
1
2
3
4

PS> $a.difference($b)
1
1
2
Issue-Enhancement Resolution-Answered

Most helpful comment

function union ($one, $two)
{
    [System.Linq.Enumerable]::union(
        [System.Collections.Generic.IEnumerable[object]] $one,
        [System.Collections.Generic.IEnumerable[object]] $two
    )
}

PS[2] (2) > union (1,2,3,4,5) (4,5,6,7)
1
2
3
4
5
6
7

All 3 comments

Why should it be in the engine?
You can use ETS to add these methods if needed.

There are types with Union and difference methods already in .net core if you need this. Hashset comes to mind, though it has the innate restriction that it can only hold unique values.

There are others as well; have a look through the System.Collections and System.Collections.Generic namespace.

function union ($one, $two)
{
    [System.Linq.Enumerable]::union(
        [System.Collections.Generic.IEnumerable[object]] $one,
        [System.Collections.Generic.IEnumerable[object]] $two
    )
}

PS[2] (2) > union (1,2,3,4,5) (4,5,6,7)
1
2
3
4
5
6
7
Was this page helpful?
0 / 5 - 0 ratings