Is there a way to do this without iterating through the List and adding the items to the ObservableCollection?
ObservableCollection<yourobjectname> result = new ObservableCollection<yourobjectname>(yourobjectlist);
//Create an observable collection TObservable.
ObservableCollection (TObservable) =new ObservableCollection (TObservable)();
//Convert List items(OldListItems) to collection
OldListItems.ForEach(x => TObservable.Add(x));
to clarify what Junior is saying (with an added example if you're using LINQ that returns an 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 );
I'm late but I want to share this interesting piece for converting a list into a ObservableCollection if you need a loop:
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;
}
You could pass an collection to the ObservableCollection constructor:
List<Product> myProds = ......
ObservableCollection<Product> oc = new ObservableCollection<Product>(myProds);
Now you have to translate these to VB.NET :)
No, there is no way to directly convert the list to an observable collection. You must add each item to the collection. However, below is a shortcut to allow the framework to enumerate the values and add them for you.
Dim list as new List(of string)
...some stuff to fill the list...
Dim observable as new ObservableCollection(of string)(list)
Even though I'm late, I wanna share a quick enhancement to Junior's answer: let the developer define the converter function used to convert observable collection objects from the source collection to the destination one.
Like the following:
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;
}