使用通用字典和或使用IDictionary进行排序 [英] using a generic Dictionary and or sorting with IDictionary

查看:411
本文介绍了使用通用字典和或使用IDictionary进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,其值在运行时确定。我可以创建它作为一个 IDictionary ,并添加到它,但我不能排序。
有没有办法创建它作为一个字典,所以我可以访问 OrderBy 或有另一种方式将其分类为 IDictionary

  void func(PropertyDescriptor prop) 
{
//创建动态字典
Type GenericTypeDictionary = typeof(Dictionary<,>);
Type SpecificTypeDictionary = GenericTypeDictionary.MakeGenericType(typeof(T),prop.PropertyType);
var genericDictionary = Activator.CreateInstance(SpecificTypeDictionary)as IDictionary;

//添加一些项目
// ....

//排序项目(此行不编译)
genericDictionary = genericDictionary.OrderBy(x => x.Value).ToDictionary(x => x.Key,x => x.Value);
}


解决方案

尝试做可能没有意义,您可以从 IDictionary 创建一个适配器到 IEnumerable< DictionaryEntry>

  IEnumerable< DictionaryEntry> EnumerateEntries(IDictionary d)
{
foreach(d)中的DictionaryEntry de
{
yield return de;
}
}

// ...

genericDictionary = EnumerateEntries(genericDictionary).OrderBy(...).ToDictionary(...);

(由于某些原因我没有进一步调查,使用 genericDictionary.Cast< ; DictionaryEntry>()而不是帮助方法对我来说不起作用,但这可能是Mono的怪癖。)


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);
}

解决方案

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.)

这篇关于使用通用字典和或使用IDictionary进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆