2009-10-20 5 views

답변

8

는 다음과 같이 해보십시오

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

나는 조금 더 간결한 무언가를 원했던 것 같아 –

2

에 대해 어떻게 :

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

나는 그것을 좋아하지만 비트를 단순화 할 수있다 : $ ht = @ {}; $ key = 0 "Key", 5, "Key2", 6 | foreach {key ($ key) {$ ht. $ key = $ _; $ key} 0 else {$ key = $ _}} –

+0

"Key"바로 앞에 줄 바꿈 문자가 있습니다. –

+0

감사합니다. 나는 타이핑이 덜한 것 같아. – 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

Bruce Payette의 글을 참고하십시오 : [PowerShell 팁 : 배열을 "이동하는 방법 ..."(http://blogs.msdn.com/b/powershell/archive/2007/02/06/powershell-tip-how -to-shift-arrays.aspx) –

+3

예. 게다가 이것은 기능적 세계에서 표준 패턴입니다. 는 이것은 ($ 다음 $ 헤드, $리스트 = $리스트) 동안 $ {H. $ 헤드 = $ 다음 } –

+0

사랑이 용액을 단축 할 수있다. – craig

1

당신의 KeyValuePairs 경우, 'Microsoft.Azure.Management.WebSites.Models.NameValuePair'명시 적이다, 다음을 사용할 수 있습니다 :

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