有没有办法在不迭代List并将项添加到ObservableCollection的情况下执行此操作?
答案 0 :(得分:39)
不,没有办法直接将列表转换为可观察的集合。您必须将每个项目添加到集合中。但是,下面是一个快捷方式,允许框架枚举值并为您添加它们。
Dim list as new List(of string)
...some stuff to fill the list...
Dim observable as new ObservableCollection(of string)(list)
答案 1 :(得分: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:)
答案 2 :(得分:3)
//Create an observable collection TObservable.
ObservableCollection (TObservable) =new ObservableCollection (TObservable)();
//Convert List items(OldListItems) to collection
OldListItems.ForEach(x => TObservable.Add(x));
答案 3 :(得分:2)
澄清Junior说的是什么(如果您使用返回IEnumerable的LINQ,则添加一个示例):
//Applications is an Observable Collection of Application in this example
List<Application> filteredApplications =
(Applications.Where( i => i.someBooleanDetail )).ToList();
Applications = new ObservableCollection<Application>( filteredApplications );
答案 4 :(得分: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;
}
答案 5 :(得分:0)
ObservableCollection<yourobjectname> result = new ObservableCollection<yourobjectname>(yourobjectlist);