What i开发者_JAVA百科s 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?
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]);
}
Function ConvertTo-Hashtable($list) {
$h = @{}
while($list) {
$head, $next, $list = $list
$h.$head = $next
}
$h
}
ConvertTo-Hashtable ("Key",1,"Key2",2)
If your list is composed of NameValuePair
objects, then you can use:
Function ConvertListOfNVPTo-Hashtable($list) {
$h = @{}
$list | ForEach-Object {
$h[$_.Name] = $_.Value
}
return $h
}
$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++])}
How about:
$ht = @{}
$key = "";
("Key",5,"Key2",6) | foreach `
{
if($key)
{
$ht.$key = $_;
$key="";
} else
{$key=$_}
}
精彩评论