2015-11-10 68 views

回答

0

使用

[email protected]{};For($i=0;$i -lt $Array1.count;$i++){$HT.Add($Array1[$i],$Array2[$i])} 

這一切就是這麼簡單,這使得一個哈希表由兩個同樣大小的數組。

編輯:好吧,我實際上正在努力使答案更公平,但感謝你爲我做這件事。我還打算爲Array classHashtable class添加MSDN頁面的鏈接以供參考。我沒有看到任何可以適應你想要做的構造函數或方法。我認爲這是因爲一個Hashtable是一個鍵盤字典,你不能有重複的鍵,而一個數組允許儘可能多的重複,如你所願。

+1

我沒不是要求任何人爲我寫一個函數。我想知道是否已經存在。給出的答案已經暗示'迭代通過兩個數組來構建哈希表' – cheezsteak

+0

我編輯了這個問題,所以它聽起來不像我要求的'代碼' – cheezsteak

+0

這不是這種問題的正確網站。也許Meta網站是,我不知道我真的不使用它。本網站旨在幫助那些在現有代碼方面遇到麻煩的人員。也許如果你發佈了你正在使用的內容,並詢問是否有更優雅的方式,或者更有效的方式來做到這一點,你的問題將落入本網站的指導方針。 – TheMadTechnician

1

LINQ附帶有需要一秒鐘的收集和選擇函數的參數是Zip() array extension method - 你可以一起使用與ToDictionary()方法做正是你想要什麼。

問題是在PowerShell中沒有對LINQ的本地語言支持。

這意味着你將有C#寫一個輔助函數,與Add-Type cmdlet編譯它,然後調用它:

# Create C# helper function 
$MemberDef = @' 
public static Hashtable ZipIt(IEnumerable<object> first, IEnumerable<object> second) 
{ 
    return new Hashtable(first.Zip(second, (k, v) => new { k, v }).ToDictionary(i => i.k, i => i.v)); 
} 
'@ 

# Compile and add it to the current runtime 
$RuntimeTypes = Add-Type -MemberDefinition $MemberDef -Name Zipper -PassThru -UsingNamespace System.Linq,System.Collections,System.Collections.Generic 

# Add-Type emits a public type "Zipper" and an private anonymous type (the lambda expression from Zip()) 
# We're only interested in the "Zipper" class 
$Zipper = $RuntimeTypes |Where-Object {$_.Name -eq 'Zipper'} 

# Now zip away! 
$Array1,$Array2 = @("a","b","c"),@(1,2,3) 
$MyHashTable = $Zipper::ZipIt($Array1,$Array2) 

$MyHashTable現在是一個普通的哈希表:

PS C:\> $MyHashTable["b"] 
2