tags:

views:

410

answers:

4

What is the best way to convert a List to a Hashtable.

Say I have a list like

("Key",$value,"Key2",$value2)

What is the shortest syntax to convert it into a Hashtable?

+3  A: 

Try the following

$table = new-object System.Collections.Hashtable
for ( $i = 0; $i -lt $list.Length; $i += 2 ) {
  $table.Add($list[$i],$list[$i+1]);
}
JaredPar
I guess I was hoping for something a bit more terse
Scott Weinstein
+1  A: 

How about:

$ht = @{}
$key = "";
("Key",5,"Key2",6) | foreach `
{  
    if($key)  
    {
        $ht.$key = $_; 
        $key=""; 
    } else 
    {$key=$_}   
}
zdan
I like that but you can simplify that a bit:$ht = @{};$key = 0"Key",5,"Key2",6 | foreach {if($key) {$ht.$key = $_;$key=0} else {$key=$_}}
Keith Hill
Watch out, the comment formatter ate my line break right before "Key",...
Keith Hill
Thanks. I guess it is less typing.
zdan
No problem. I really like that you can set a hashtable entry using property syntax when the property name is a variable e.g. $ht.$key = $_. That just strikes me as nifty. :-)
Keith Hill
A: 
$h = @{}  
0..($l.count - 1) | ? {$_ -band 1} | % {$h.Add($l[$_-1],$l[$_])}  

$h = @{}  
0..($l.count - 1) | ? {$_ -band 1} | % {$h.($l[$_-1]) = $l[$_]}  

$h = @{}  
$i = 0  
while ($i -lt $l.count) {$h.Add($l[$i++],$l[$i++])}
+2  A: 
Function ConvertTo-Hashtable($list) {
    $h = @{}

    while($list) {
        $head, $next, $list = $list
        $h.$head = $next
    }

    $h
}

ConvertTo-Hashtable ("Key",1,"Key2",2)
Doug Finke
see also Bruce Payette's post: [PowerShell Tip: How to “shift” arrays…](http://blogs.msdn.com/b/powershell/archive/2007/02/06/powershell-tip-how-to-shift-arrays.aspx)
Emperor XLII
Yes. Plus this is a standard pattern in the functional world.It can be shortened to while($head, $next, $list = $list) { $h.$head = $next}
Doug Finke