2009-10-20 16 views

Respuesta

8

intente lo siguiente

$table = new-object System.Collections.Hashtable 
for ($i = 0; $i -lt $list.Length; $i += 2) { 
    $table.Add($list[$i],$list[$i+1]); 
} 
+4

Supongo que esperaba algo un poco más escueto –

2

¿Qué tal:

$ht = @{} 
$key = ""; 
("Key",5,"Key2",6) | foreach ` 
{ 
    if($key) 
    { 
     $ht.$key = $_; 
     $key=""; 
    } else 
    {$key=$_} 
} 
+1

Me gusta, pero puede simplificar un poco: $ ht = @ {}; $ clave = 0 "Clave", 5, "Key2", 6 | foreach {if ($ key) {$ ht. $ key = $ _; $ key = 0} else {$ key = $ _}} –

+0

Cuidado, el formateador de comentarios comió mi salto de línea justo antes de "Key", .. –

+0

Gracias. Supongo que es menos tipeo. – zdan

2
$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++])} 
11
Function ConvertTo-Hashtable($list) { 
    $h = @{} 

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

    $h 
} 

ConvertTo-Hashtable ("Key",1,"Key2",2) 
+1

vea también la publicación de Bruce Payette: [Consejo de PowerShell: Cómo "cambiar" las matrices ...] (http://blogs.msdn.com/b/powershell/archive/2007/02/06/powershell-tip-how -to-shift-arrays.aspx) –

+3

Sí. Además, este es un patrón estándar en el mundo funcional. Se puede acortarse a tiempo ($ cabeza, $ A continuación, la lista $ = $ lista) {$ h. $ = $ Cabeza junto } –

+0

amor esta solución. – craig

1

Si sus KeyValuePairs, son explícitamente 'Microsoft.Azure.Management.WebSites.Models.NameValuePair', entonces usted puede usar:

Function ConvertListOfNVPTo-Hashtable($list) { 
    $h = @{} 
    $list | ForEach-Object { 
     $ht[$_.Name] = $_.Value 
    } 
    return $h 
} 
Cuestiones relacionadas