将 LINQ 结果转换为 ObservableCollection [英] Cast LINQ result to ObservableCollection
问题描述
事实上,它是一个 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.
我运行了一个 LINQ 查询.结果是;
I run a LINQ query. The result is an;
IEnumerable<MyClass>
我想把结果放到一个 ObservableCollection 中;
I want to put the result into an ObservableCollection;
ObservableCollection<MyClass>
我该怎么做这个演员表?(无需运行 IEnumerable 并将元素复制到 ObservableCollection).我注意到 LINQ 有一些 To..() 函数,但它似乎对这个演员没有帮助..?
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..?
推荐答案
只需使用:
ObservableCollection<Foo> x = new ObservableCollection<Foo>(enumerable);
这将完成所需的复制.无法观察实时查询的变化 - 尽管 ObservableQuery
的想法很有趣(尽管具有挑战性).
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);
}
这篇关于将 LINQ 结果转换为 ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!