C# - 将匿名类型转换为可观察集合
我有一个返回匿名类型的 LINQ 语句。我需要在我的 Silverlight 应用程序中将此类型设为 ObservableCollection。但是,我可以将其最接近
List myObjects;
有人可以告诉我该怎么做吗?
ObservableCollection<MyTasks> visibleTasks = e.Result;
var filteredResults = from visibleTask in visibleTasks
select visibleTask;
filteredResults = filteredResults.Where(p => p.DueDate == DateTime.Today);
visibleTasks = filteredResults.ToList(); // This throws a compile time error
如何从匿名类型转变为可观察集合?
谢谢
I have a LINQ statement that returns an anonymous type. I need to get this type to be an ObservableCollection in my Silverlight application. However, the closest I can get it to a
List myObjects;
Can someone tell me how to do this?
ObservableCollection<MyTasks> visibleTasks = e.Result;
var filteredResults = from visibleTask in visibleTasks
select visibleTask;
filteredResults = filteredResults.Where(p => p.DueDate == DateTime.Today);
visibleTasks = filteredResults.ToList(); // This throws a compile time error
How can I go from a anonymous type to an observable collection?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如 Ekin 建议的那样,您可以编写一个通用方法,将任何
IEnumerable
转换为ObservableCollection
。与使用构造函数创建ObservableCollection
的新实例相比,这有一个显着的优势 - C# 编译器能够在调用方法时自动推断泛型类型参数,因此您无需编写的元素。这允许您创建匿名类型的集合,否则这是不可能的(例如,当使用构造函数时)。对 Ekin 版本的一项改进是将该方法编写为扩展方法。按照通常的命名模式(例如
ToList
或ToArray
),我们可以将其称为ToObservableCollection
:现在您可以创建一个包含匿名类型的可观察集合从 LINQ 查询返回,如下所示:
As Ekin suggests, you can write a generic method that turns any
IEnumerable<T>
into anObservableCollection<T>
. This has one significant advantage over creating a new instance ofObservableCollection
using constructor - the C# compiler is able to infer the generic type parameter automatically when calling a method, so you don't need to write the type of the elements. This allows you to create a collection of anonymous types, which wouldn't be otherwise possible (e.g. when using a constructor).One improvement over Ekin's version is to write the method as an extension method. Following the usual naming pattern (such as
ToList
orToArray
), we can call itToObservableCollection
:Now you can create an observable collection containing anonymous types returned from a LINQ query like this:
像这样的事情可以使用类型推断功能来完成这项工作:
Something like this would do the job using type inference features:
你应该能够这样做:
You should just be able to do this:
您确定您的对象确实是一个
ObservableCollection
吗?如果是,您可以直接转换:visibleTasks = (ObservableCollection)filteredResults;Are you sure that your object is an
ObservableCollection
indeed? If yes, you can just cast:visibleTasks = (ObservableCollection)filteredResults;
尝试:
(filteredResults 将包含您想要的列表)
Try:
(filteredResults will contain your desired list)