Does a zip function already exist that would combine two equally sized arrays into a HashTable or some inline method? Or is the only way to build the HashTable in a for loop.
2 Answers
Use
$HT=@{};For($i=0;$i -lt $Array1.count;$i++){$HT.Add($Array1[$i],$Array2[$i])}
That's all there is to it, that makes a hashtable from two equally sized arrays.
Edit: Ok, I was actually working on making the answer more civil, but thank you for doing that for me. I was also going to add links to the MSDN pages for the Array class, and Hashtable class for reference. I see no constructors or methods on either of those that would accommodate what you are trying to do. I assume that this is because a Hashtable is a keyed dictionary where you can not have duplicate keys, while an array allows for as many duplicates as you could want.
5 Comments
LINQ comes with the Zip() array extension method that takes a second collection and a selector function as its argument - you could use that together with the ToDictionary() method to do exactly what you want.
The problem is that there is no native language support for LINQ in PowerShell.
That means you'll have to write a helper function in C#, compile it with the Add-Type cmdlet and then invoke it:
# Create C# helper function
$MemberDef = @'
public static Hashtable ZipIt(IEnumerable<object> first, IEnumerable<object> second)
{
return new Hashtable(first.Zip(second, (k, v) => new { k, v }).ToDictionary(i => i.k, i => i.v));
}
'@
# Compile and add it to the current runtime
$RuntimeTypes = Add-Type -MemberDefinition $MemberDef -Name Zipper -PassThru -UsingNamespace System.Linq,System.Collections,System.Collections.Generic
# Add-Type emits a public type "Zipper" and an private anonymous type (the lambda expression from Zip())
# We're only interested in the "Zipper" class
$Zipper = $RuntimeTypes |Where-Object {$_.Name -eq 'Zipper'}
# Now zip away!
$Array1,$Array2 = @("a","b","c"),@(1,2,3)
$MyHashTable = $Zipper::ZipIt($Array1,$Array2)
$MyHashTable is now a regular hashtable:
PS C:\> $MyHashTable["b"]
2