3

Okay, I have some hash tables I need to combine using PowerShell. Here is an example of the format:

$table1 = @{"A" = "1,2";
            "B" = "3,4";
            "C" = "5,6"}

$table2 = @{"A" = "3";
            "B" = "5";
            "C" = "7"}

I need to combine the tables in order to create the following table:

$newTable = @{"A" = "1,2,3";
              "B" = "3,4,5";
              "C" = "5,6,7"}

Basically, the keys and values need to be compared. If the values are different, they needed to be added together. Thanks!

3 Answers 3

1

Here's a slightly different approach:

$table1 = @{"A" = "1,2";
            "B" = "3,4";
            "C" = "5,6"}

$table2 = @{"A" = "3";
            "B" = "5";
            "C" = "7"}

$ht = $table1.Clone()
$table2.GetEnumerator() | % {$ht[$_.Key] += ",$($_.Value)"}
$ht

Name                           Value
----                           -----
C                              5,6,7
A                              1,2,3
B                              3,4,5
Sign up to request clarification or add additional context in comments.

1 Comment

Well the two approaches aren't exactly functionally equivalent. The approach I propose pulls in everything from $table2 - not just the KV pairs that match keys with $table1.
0

You can use the GetEnumerator() method to loop through the values like below.

This will become much more complicated if you have uneven key distribution (some exist only in $table1 and others only in $table2) but it works for your example scenario.

$table1 = @{"A" = "1,2";
            "B" = "3,4";
            "C" = "5,6"}

$table2 = @{"A" = "3";
            "B" = "5";
            "C" = "7"}


$NewTable = @{}

$table1.GetEnumerator() | 
%   {
    $NewTable.Add($_.Key, ("$($_.Value),$($table2[$_.Key])"))
    }

Comments

0

How about:

$table1 = @{"A" = "1,2";
            "B" = "3,4";
            "C" = "5,6"}

$table2 = @{"A" = "2";
            "B" = "5";
            "C" = "7"}

    $newTable = @{}

    function AddToTable($table)
    {
        $table.GetEnumerator() | 
        % {
          if(!$newTable.ContainsKey($_.Key)) {$newTable.Add($_.Key, $_.Value)}
          else {$newTable[$_.Key] += ",$($_.Value)"}
          $newTable[$_.Key] = @($newTable[$_.Key].Split(",") | Get-Unique | Sort-Object) -Join "," 
        }
    }

    AddToTable($table1)
    AddToTable($table2)

Comments

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.