2009-10-20 11 views

Odpowiedz

8

Wypróbuj następujące

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

Chyba miałem nadzieję na coś bardziej zwięzłego. –

2

Jak o:

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

Podoba mi się, ale możesz to nieco uprościć: $ ht = @ {}; $ key = 0 "Key", 5, "Key2", 6 | foreach {if ($ key) {$ ht. $ key = $ _; $ key = 0} else {$ key = $ _}} –

+0

Uwaga, formater komentarzy zjadł mój wiersz tuż przed "Key", .. . –

+0

Dzięki. Sądzę, że to mniej pisania. – 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

Zobacz także post Bruce Payette: [Porada PowerShell: Jak "przesunąć" tablice ...] (http://blogs.msdn.com/b/powershell/archive/2007/02/06/powershell-tip-how -to-shift-arrays.aspx) –

+3

Tak. Dodatkowo jest to standardowy wzorzec w świecie funkcjonalnym. To może być skrócony do czas ($, $ następnej głowicy, $ list = $ list) { $ H. = $ $ Głowicy obok } –

+0

Miłość tego rozwiązania. – craig

1

Jeśli Twoje KeyValuePairs są wyraźnie 'Microsoft.Azure.Management.WebSites.Models.NameValuePair' następnie możesz użyć:

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