类似下面的东西会起作用(没有经过语法检查,抱歉):
// 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 个,并且您需要按类别名称随机重复地找到它们,那么 Dictionary 是正确的方法,因为它对事物进行哈希处理以加快搜索速度(想想数据库中表中的索引)。但是,如果您有 10,000 个但只需要找到其中的 2 个,反之亦然,只有 10 个,那么建立快速搜索功能的开销就被浪费了。因此,Dictionary vs other 的最佳答案是“如果这是在数据库表中,你会索引它吗?”