问题
I have a dictionary where the value is determined at runtime. I can create it as an IDictionary
and add to it fine however I can't sort.
Is there a way to create it as a Dictionary
so I can access OrderBy
or is there another way to sort it as an 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);
}
回答1:
Ignoring the point that what you're trying to do might not make sense, you can just create an adapter from IDictionary
to IEnumerable<DictionaryEntry>
:
IEnumerable<DictionaryEntry> EnumerateEntries(IDictionary d)
{
foreach (DictionaryEntry de in d)
{
yield return de;
}
}
// ...
genericDictionary = EnumerateEntries(genericDictionary).OrderBy(…).ToDictionary(…);
(For some reason I didn't investigate further, using genericDictionary.Cast<DictionaryEntry>()
instead of the helper method didn't work for me, but that might be a Mono quirk.)
来源:https://stackoverflow.com/questions/15045790/using-a-generic-dictionary-and-or-sorting-with-idictionary