2009-04-08 66 views
12

我在目前返回一个IList,我想找个变成一个ObservableCollection所以这个最干净的方式Silverlight应用程序的方法:的IList <T>到的ObservableCollection <T>

public IList<SomeType> GetIlist() 
{ 
    //Process some stuff and return an IList<SomeType>; 
} 

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<SomeType> myList = GetIlist 
    foreach (SomeType currentItem in myList) 
    { 
     SomeCollection.Add(currentEntry); 
    } 
} 

的ObservableCollection没有一个将以IList或IEnumerable作为参数的构造函数,所以我不能简单地将其添加到一个参数中。有没有其他选择看起来更像选项1,我错过了,还是我太挑剔了,选项2确实是一个合理的选择。

另外,如果选项2是唯一的实际选项,是否有理由在IEnurerable上使用IList,如果我真的要处理这个问题就是迭代返回值并将其添加到其他值那种收藏?

在此先感谢

+2

的Silverlight 4更新:DOES的ObservableCollection现在有一个构造函数,将牛逼以IList或IEnumerable作为参数 – 2010-11-01 00:36:17

回答

28

你可以写一个快速和肮脏的扩展方法,可以很容易

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable) { 
    var col = new ObservableCollection<T>(); 
    foreach (var cur in enumerable) { 
    col.Add(cur); 
    } 
    return col; 
} 

现在你可以只写

return GetIlist().ToObservableCollection(); 
+2

我已经考虑过了,可能应该这么说。大多数情况下,我想确保没有什么可以让我失踪的东西。 – 2009-04-08 20:19:45

+1

@Steve不幸的是我不'认为你忽略了任何东西。 – JaredPar 2009-04-08 20:22:08

+1

Jared,对你的语法进行了小小的修改 - public static ObservableCollection ToObservableCollection(this ... should be public static ObservableCollection ToObservableCollection (this ...我没有足够的代表编辑你的文章,请修正。 – 2009-04-09 20:04:31

1
 IList<string> list = new List<string>(); 

     ObservableCollection<string> observable = 
      new ObservableCollection<string>(list.AsEnumerable<string>()); 
2

是JaredPar给你的是在Silverlight你最好的选择扩展方法。它使您能够通过引用名称空间自动将任何IEnumerable变为可观察集合,并减少代码重复。没有什么内置的,不像WPF,它提供了构造函数选项。

ib。

2

不重新线程但的ObservableCollection一个构造函数IEnumerable已添加到Silverlight 4的

2

Silverlight 4中确实有刚才'new up' an ObservableCollection

下面是在Silverlight 4的缩短扩展方法可能的能力。

public static class CollectionUtils 
{ 
    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> items) 
    { 
     return new ObservableCollection<T>(items); 
    } 
} 
1
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 
相关问题