How do I convert a List(Of T) to an ObservableCollection(Of T) in VB.NET?

50,680

Solution 1

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)

Solution 2

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 :)

Solution 3

//Create an observable collection TObservable.

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

//Convert List items(OldListItems) to collection

OldListItems.ForEach(x => TObservable.Add(x));

Solution 4

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 );

Solution 5

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;
    }
Share:
50,680
Rob Sobers
Author by

Rob Sobers

I'm a software developer with a love for problem solving, design, and technology in general. I'm currently working at Fog Creek Software in New York.

Updated on July 09, 2022

Comments

  • Rob Sobers
    Rob Sobers almost 2 years

    Is there a way to do this without iterating through the List and adding the items to the ObservableCollection?

  • MarkJ
    MarkJ over 14 years
    That's C# not VB.NET but +1 anyway for solving it for any IEnumerable (and also for being late!)
  • RredCat
    RredCat almost 14 years
    Cool joke! It is real subtle humor!!
  • Bhavesh Patadiya
    Bhavesh Patadiya over 11 years
    please put here description of your answer.