将 ObservableCollection<myclass> 复制到 ObservableCollection<KeyValuePair<string,object>>
Copy ObservableCollection<myclass> to ObservableCollection<KeyValuePair<string,object>>
我想知道是否有人可以告诉我一个更简单的方法来将我的 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));
}
您可以这样使用 ToDictionary()
:
ObservableCollection<KeyValuePair<string, object>> KeyValueCollection =
new ObservableCollection<KeyValuePair<string, object>>(collection.ToDictionary(
entry => t.Name,
entry => (object)entry));
这会创建一个 Dictionary<string,object>
,方法是选择 myclass
的 Name
属性 作为键,将 myclass
转换为 object
作为值。
由于 Dictionary<string,object>
是一个 IEnumerable<KeyValuePair<string, object>>
,您可以将它用作 ObservableCollection<KeyValuePair<string, object>>
.
的构造函数参数
我想知道是否有人可以告诉我一个更简单的方法来将我的 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));
}
您可以这样使用 ToDictionary()
:
ObservableCollection<KeyValuePair<string, object>> KeyValueCollection =
new ObservableCollection<KeyValuePair<string, object>>(collection.ToDictionary(
entry => t.Name,
entry => (object)entry));
这会创建一个 Dictionary<string,object>
,方法是选择 myclass
的 Name
属性 作为键,将 myclass
转换为 object
作为值。
由于 Dictionary<string,object>
是一个 IEnumerable<KeyValuePair<string, object>>
,您可以将它用作 ObservableCollection<KeyValuePair<string, object>>
.