Cast LINQ result to ObservableCollection

拥有回忆 提交于 2019-12-17 07:13:22

问题


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


回答1:


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



回答2:


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

var observable = new ObservableCollection<Foo>(linqResults);



回答3:


You can use an ObservableCollection constructor for this:

ObservableCollection<MyClass> obsCol = 
        new ObservableCollection<MyClass>(myIEnumerable);



回答4:


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




回答5:


I wrote this library a few years ago.

https://github.com/wasabii/OLinq

It doesn't do exactly what you probably want, it does more. It's a Linq query provider which parses the expression tree, attaches to the referenced collections, and exposes another collection which emits events upon changes.

It's missing a few Linq operators. But the code base is not hard to extend.




回答6:


You need my ObservableComputations library maybe. That is .NET API for computations over INotifyPropertyChanged and INotifyColectionChanged (ObservableCollection) objects. Results of the computations are INotifyPropertyChanged and INotifyColectionChanged (ObservableCollection) objects.



来源:https://stackoverflow.com/questions/1465285/cast-linq-result-to-observablecollection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!