2008-10-28 95 views

回答

38

不,沒有辦法直接將列表轉換爲可觀察集合。您必須將每個項目添加到集合中。但是,下面是允許框架枚舉值併爲您添加它們的快捷方式。

Dim list as new List(of string) 
...some stuff to fill the list... 
Dim observable as new ObservableCollection(of string)(list) 
18

我來晚了,但我想,如果你需要一個循環來分享這個有趣的一塊用於將列表轉換成的ObservableCollection:

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll) 
{ 
    var c = new ObservableCollection<T>(); 
    foreach (var e in coll) c.Add(e); 
    return c; 
} 

你可以傳遞一個收集到的ObservableCollection構造:

List<Product> myProds = ...... 
ObservableCollection<Product> oc = new ObservableCollection<Product>(myProds); 

現在,你必須將這些轉化爲VB.NET :)

+0

這是C#不VB.NET,但無論如何+1解決它任何IEnumerable(也爲遲到!) – MarkJ 2009-08-25 13:32:39

+0

酷玩笑!這是真正微妙的幽默! – RredCat 2010-05-28 10:27:36

2

到澄清少年是說(與添加的例子,如果你正在使用LINQ返回一個IEnumerable):

//Applications is an Observable Collection of Application in this example 
List<Application> filteredApplications = 
     (Applications.Where(i => i.someBooleanDetail)).ToList(); 
Applications = new ObservableCollection<Application>(filteredApplications); 
2
//Create an observable collection TObservable. 

ObservableCollection (TObservable) =new ObservableCollection (TObservable)(); 

//Convert List items(OldListItems) to collection 

OldListItems.ForEach(x => TObservable.Add(x)); 
0
ObservableCollection<yourobjectname> result = new ObservableCollection<yourobjectname>(yourobjectlist); 
1

即使我遲到了,我想分享一個快速增強Junior答案:讓開發人員定義用於將源集合中的可觀察集合對象轉換爲目標集合對象的轉換器函數。

類似如下:

public static ObservableCollection<TDest> ToObservableCollection<TDest, TSource>(this IEnumerable<TSource> coll, Func<TSource, TDest> converter) 
    { 
     var c = new ObservableCollection<TDest>(); 
     foreach (var e in coll) 
     { 
      c.Add(converter(e)); 
     } 
     return c; 
    } 
相關問題