IList 到ObservableCollection
我在Silverlight应用程序中有一个方法,当前返回一个IList,我想找到最简单的方法将其转换为ObservableCollection所以:
public IList GetIlist() { //Process some stuff and return an IList; } public void ConsumeIlist() { //SomeCollection is defined in the class as an ObservableCollection //Option 1 //Doesn't work - SomeCollection is NULL SomeCollection = GetIlist() as ObservableCollection //Option 2 //Works, but feels less clean than a variation of the above IList myList = GetIlist foreach (SomeType currentItem in myList) { SomeCollection.Add(currentEntry); } }
ObservableCollection没有一个构造函数,它将IList或IEnumerable作为参数,所以我不能简单地新建一个。 是否有一种替代方案看起来更像是我缺少的选项1,或者我只是在这里太挑剔而且选项2确实是一个合理的选择。
此外,如果选项2是唯一真正的选项,是否有理由在IEnurerable上使用IList,如果我真正要做的就是迭代返回值并将其添加到其他类型的集合中?
提前致谢
你可以写一个快速而又脏的扩展方法来简化它
public static ObservableCollection ToObservableCollection (this IEnumerable enumerable) { var col = new ObservableCollection (); foreach ( var cur in enumerable ) { col.Add(cur); } return col; }
现在你可以写
return GetIlist().ToObservableCollection();
呃……
ObservableCollection
确实有一个构造函数 ,它将采用IEnumerable
, IList
派生自IEnumerable
。
所以你可以“只是一个新的”
JaredPar为您提供的扩展方法是Silverlight中的最佳选择。 它使您能够通过引用命名空间自动将任何IEnumerable转换为可观察集合,并减少代码重复。 与WPF不同,它没有内置任何内容,它提供了构造函数选项。
IB。
不重新打开线程,但是带有IEnumerable的 ObservableCollection构造函数已添加到silverlight 4
Silverlight 4 DOES能够“新建”一个ObservableCollection
这是Silverlight 4中可能缩短的扩展方法。
public static class CollectionUtils { public static ObservableCollection ToObservableCollection (this IEnumerable items) { return new ObservableCollection (items); } }
IList list = new List (); ObservableCollection observable = new ObservableCollection (list.AsEnumerable ());
Dim taskList As ObservableCollection(Of v2_Customer) = New ObservableCollection(Of v2_Customer) ' Dim custID As Guid = (CType(V2_CustomerDataGrid.SelectedItem, _ ' v2_Customer)).Cust_UUID ' Generate some task data and add it to the task list. For index = 1 To 14 taskList.Add(New v2_Customer() With _ {.Cust_UUID = custID, .Company_UUID, .City }) Next Dim taskListView As New PagedCollectionView(taskList) Me.CustomerDataForm1.ItemsSource = taskListView