将LINQ结果转换为ObservableCollection [英] Cast LINQ result to ObservableCollection

查看:281
本文介绍了将LINQ结果转换为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< T> 的想法是一个有趣的(虽然具有挑战性)。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆