Converting ObservableCollection to List?

95,803

Solution 1

Depending on the type of object in the ObservableCollection... I'll assume it's an int for this example:

IEnumerable<int> obsCollection = (IEnumerable<int>)GetCollection();
var list = new List<int>(obsCollection);

Solution 2

Just need to add the namespace using System.Linq;

and use the method ToList() in the ObservableCollection object

Solution 3

Given that ObservableCollection<T> implements IEnumerable<T> you can give it to the constructor of List<T>:

List<T> myList = new List<T>(myObservableCollection);

Where T is the type of the items in the collection.

Solution 4

ObservableCollection implements IList<T>, so you should be able to use ToList() on it.

http://msdn.microsoft.com/en-us/library/bb342261.aspx

Solution 5

The Items property returns an IList. See http://msdn.microsoft.com/en-us/library/ms132435.aspx

Share:
95,803
Shawn Mclean
Author by

Shawn Mclean

:)

Updated on November 08, 2021

Comments

  • Shawn Mclean
    Shawn Mclean over 2 years

    How does one convert an ObservableCollection to a List of the held objects?

  • Matthew Scharley
    Matthew Scharley over 14 years
    Only in 3.5 with LINQ, I'd argue just creating the list yourself from an IEnumerable is easier. This still involves a cast if you've only got an object.
  • Sam Harwell
    Sam Harwell over 14 years
    @Matthew, I rewrote it without the unnecessary explicit cast - change it back if you don't like it this way.
  • Matthew Scharley
    Matthew Scharley over 14 years
    @280Z28: According to the original question, he's getting an object as his collection, in which case a cast is needed somewhere.
  • Shawn Mclean
    Shawn Mclean over 14 years
    why cast it to IEnumerable<>? Couldn't I just past it in the new List<>(here)?
  • Matthew Scharley
    Matthew Scharley over 14 years
    You indicated in your question that you were recieving it as an object. If you are actually recieving it as an ObservableCollection, then yes, the cast is unnecessary.
  • Matthew Scharley
    Matthew Scharley over 14 years
    That said, yes, you can do it on one line. I just dislike really long lines in code snippets here (scrolling sucks, everyone knows that).
  • cdonner
    cdonner over 3 years
    I wish I would remember this the next time I run into this very issue.