56

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

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

6 Answers6

86

Just need to add the namespace using System.Linq;

and use the method ToList() in the ObservableCollection object

Jaider
  • 14,268
  • 5
  • 75
  • 82
71

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);
Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
  • @Matthew, I rewrote it without the unnecessary explicit cast - change it back if you don't like it this way. – Sam Harwell Nov 01 '09 at 22:52
  • 1
    @280Z28: According to the original question, he's getting an object as his collection, in which case a cast is needed somewhere. – Matthew Scharley Nov 01 '09 at 22:57
  • 1
    why cast it to IEnumerable<>? Couldn't I just past it in the new List<>(here)? – Shawn Mclean Nov 02 '09 at 04:06
  • 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 Nov 02 '09 at 04:14
  • 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). – Matthew Scharley Nov 02 '09 at 04:16
26

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.

GraemeF
  • 11,327
  • 5
  • 52
  • 76
5

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

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

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • 1
    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. – Matthew Scharley Nov 01 '09 at 22:44
2

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

LJM
  • 6,284
  • 7
  • 28
  • 30
0

I think the issue here is that ObservableCollection might be modified on the fly when you try to convert it to a List or use as such, so you might need to use a watchdog timer of sorts until ObservableCollection finishes