像下面的內容將工作(不是語法檢查這個,不好意思):
// This requires the array of Categories to have no duplicates.
public Dictionary<string, PdfOutline> BuildUpMyCollectionOfOutlines(string[] categories)
{
return categories.ToDictionary(cat => new KeyValuePair<string, PdfOutline>(cat, null));
}
如果你做這種方式,您可以稍後再消耗的結果作爲這樣的(雖然有一個函數來做到這是愚蠢的,只是我的方式來告訴你如何使用它):
public PdfOutline GetOutlineByCategory(Dictionary<string, PdfOutline> outlines, string category)
{
// This will be problematic if the category isn't actually in the dictionary.
return outlines[category];
}
你是否應該使用Dictionary<string, PdfOutline>
與別的東西,像一個List<KeyValuePair<string, PdfOutline>>
取決於1),你會怎麼這麼多已經和2)你將如何訪問它們。例如,如果您有10,000個,並且您需要隨機並重覆按類別名稱查找它們,那麼字典是正確的方法,因爲它可以縮短搜索速度(可以考慮數據庫中的表中的索引)。但是,如果您有10,000個,但只需要找到其中的2個,反之亦然,則只有10個,那麼構建該快速搜索功能的開銷就會被浪費。因此Dictionary與其他問題最好的回答是「如果這是在數據庫表中,你會索引它嗎?」