我有一個字典,其中的值是在運行時確定的。我可以創建它作爲IDictionary
並添加到它很好,但我無法排序。 有沒有辦法將它創建爲Dictionary
,所以我可以訪問OrderBy
或者有其他方法將它排序爲IDictionary
?使用通用字典和或用IDictionary排序
void func (PropertyDescriptor prop)
{
//Create dynamic dictionary
Type GenericTypeDictionary = typeof(Dictionary<,>);
Type SpecificTypeDictionary = GenericTypeDictionary.MakeGenericType(typeof(T), prop.PropertyType);
var genericDictionary = Activator.CreateInstance(SpecificTypeDictionary) as IDictionary ;
//Add some items to it
//....
//Sort items (this line doesn't compile)
genericDictionary = genericDictionary.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
}
可能重複的[你如何按值排序C#字典?](http:// stackoverflow。 COM /問題/ 289 /怎麼辦,你排序-AC鋒利字典由-v alue) – 2013-02-23 21:17:33
不會對字典進行排序,然後調用'ToDictionary()'最終只是以random-ish命令中的項目結束? – millimoose 2013-02-23 21:23:54
Tim的鏈接只有在您的字典對鍵和值都是通用的時纔有效。是否可以使PropertyDescriptor prop成爲通用成員,因此您可以將特定Dictionary用作字典? –
Larry
2013-02-23 21:26:20