Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast LINQ result to ObservableCollection

Tags:

c#

casting

linq

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..?

like image 291
stiank81 Avatar asked Sep 23 '09 10:09

stiank81


3 Answers

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);
}
like image 103
Jon Skeet Avatar answered Nov 19 '22 08:11

Jon Skeet


var linqResults = foos.Where(f => f.Name == "Widget");

var observable = new ObservableCollection<Foo>(linqResults);
like image 16
Dave Markle Avatar answered Nov 19 '22 08:11

Dave Markle


You can use an ObservableCollection constructor for this:

ObservableCollection<MyClass> obsCol = 
        new ObservableCollection<MyClass>(myIEnumerable);
like image 11
bruno conde Avatar answered Nov 19 '22 06:11

bruno conde