投LINQ结果的ObservableCollection [英] Cast LINQ result to ObservableCollection

查看:214
本文介绍了投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已经得到了几把。()函数,但似乎并没有帮助我这个投..?

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&LT; T&GT; 是一个有趣的(尽管具有挑战性)有一个

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天全站免登陆