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!

E_MAN
  • 31
  • 1
  • 2

3 Answers3

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
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • 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. – Keith Hill Dec 07 '12 at 22:43
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])"))
    }
JNK
  • 63,321
  • 15
  • 122
  • 138
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)
Dave Sexton
  • 10,768
  • 3
  • 42
  • 56