using a generic Dictionary and or sorting with IDictionary

…衆ロ難τιáo~ 提交于 2019-12-11 01:57:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!