tags:

views:

2189

answers:

4

The fact that it is a LINQ result might perhaps not be relevant for the question, but I'm mentioning it anyway - since this is the context which has resulted in this question.

I run a LINQ query. The result is an;

IEnumerable<MyClass>

I want to put the result into an ObservableCollection;

ObservableCollection<MyClass>

How do I do this cast? (without running through the IEnumerable and copying elements to the ObservableCollection). I notice LINQ has got a few To..() functions, but it doesn't seem to help me for this cast..?

+10  A: 

Just use:

ObservableCollection<Foo> x = new ObservableCollection<Foo>(enumerable);

That will do the required copying. There's no way of observing changes to the live query - although the idea of an ObservableQuery<T> is an interesting (though challenging) one.

If you want an extension method to do this, it's simple:

public static ObservableCollection<T> ToObservableCollection<T>
    (this IEnumerable<T> source)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    return new ObservableCollection<T>(source);
}
Jon Skeet
Thx! This works. A new issue then is that - as this is an ObservableCollection - I need to raise a PropertyChanged event for the property holding the ObservableCollection - as it is not the content of the collection that has changed, but in fact the property holding the collection. I guess it shouldn't be a problem to do this though. Keeping the existing ObservableCollection I guess I have to do a manual foreach-copy..?
stiank81
@bambuska: I'm afraid I don't really understand your question.
Jon Skeet
Oh, okay.. Well - never mind. I got what I needed anyway. Thx!
stiank81
Anybody now how to achieve this in Silverlight 3.0, where only the default new ObservableCollection<Foo>() constructor is available?
Bernard Vander Beken
+1  A: 

You can use an ObservableCollection constructor for this:

ObservableCollection<MyClass> obsCol = 
        new ObservableCollection<MyClass>(myIEnumerable);
bruno conde
+1  A: 
var linqResults = foos.Where(f => f.Name == "Widget");

var observable = new ObservableCollection<Foo>(linqResults);
Dave Markle
+1  A: 

IEnumerable is only the interface.

You would need to copy the content from the IEnumerable into the ObservableCollection. You can do this by passing your IEnumerable into the constructor of the ObersvableCollection when you create a new one

Heiko Hatzfeld