如何在Silverlight中使用LINQ创建ObservableCollection [英] How to create an ObservableCollection using LINQ in Silverlight

查看:47
本文介绍了如何在Silverlight中使用LINQ创建ObservableCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在非Silverlight的世界中,很容易使用LINQ创建ObservableCollection.这是因为ObservableCollection类具有接受任何IEnumerable< T>或List< T>的构造函数.但是,Silverlight版本没有!这意味着代码如下:

In a non-Silverlight world, it is easy to use LINQ to create an ObservableCollection. This is because the ObservableCollection class has constructors that accept any IEnumerable<T> or List<T>. However, the Silverlight version does not! This means that code such as:

var list = (from item in e.Result
            select new ViewModel(item)).ToList();

Items = new System.Collections.ObjectModel.ObservableCollection<ViewModel>(list);

在Silverlight中不起作用.

will not work in Silverlight.

除了诉诸for-for语句之外,还有其他选择可以使这项工作吗?

Is there another option to make this work besides resorting to a for-each statement?

推荐答案

如果您使用的是Silverlight 4,那行得通. 试试这个:

Well That works if you are using Silverlight 4. try this:

public static class CollectionExtensions
    {
        public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll)
        {
            var c = new ObservableCollection<T>();
            foreach (var e in coll)
                c.Add(e);
            return c;
        }
    }

位于: http://forums.silverlight.net/forums/p/39487/262505.aspx

这篇关于如何在Silverlight中使用LINQ创建ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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