将ObservableCollection <myclass>复制到ObservableCollection <keyvaluepair <string,object>&gt;

时间:2016-05-24 06:36:49

标签: c# observablecollection

我想知道是否有人可以告诉我更简单的方法将ObservableCollection<myclass>复制到ObservableCollection<KeyValuePair<string, object>>

这就是我的表现:

 KeyValueCollection=new ObservableCollection<KeyValuePair<string, object>>();

 //Collection = ObservableCollection<myclass>
 foreach (var entry in Collection)
        {
             KeyValueCollection.Add(new KeyValuePair<string, object>(entry.Name,entry));
        }

1 个答案:

答案 0 :(得分:1)

您可以像这样使用ToDictionary()

ObservableCollection<KeyValuePair<string, object>> KeyValueCollection =
          new ObservableCollection<KeyValuePair<string, object>>(collection.ToDictionary(
              entry => t.Name, 
              entry => (object)entry));

这会通过选择Dictionary<string,object>的{​​{1}}属性作为将Name转换为myclass作为值来创建myclass

由于objectDictionary<string,object>,您可以将其用作IEnumerable<KeyValuePair<string, object>>的构造函数参数。