2009-04-08 33 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 
相關問題