IList的< T>到的ObservableCollection< T>

编程入门 行业动态 更新时间:2024-10-25 00:24:18
本文介绍了IList的< T>到的ObservableCollection< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在目前返回一个IList,我想找到把它变成一个ObservableCollection这样最干净的方式Silverlight应用程序的方法:

I have a method in a Silverlight app that currently returns an IList and I would like to find the cleanest way to turn this into an ObservableCollection so:

public IList<SomeType> GetIlist() { //Process some stuff and return an IList<SomeType>; } public void ConsumeIlist() { //SomeCollection is defined in the class as an ObservableCollection //Option 1 //Doesn't work - SomeCollection is NULL SomeCollection = GetIlist() as ObservableCollection //Option 2 //Works, but feels less clean than a variation of the above IList<SomeType> myList = GetIlist foreach (SomeType currentItem in myList) { SomeCollection.Add(currentEntry); } }

的ObservableCollection没有一个构造函数,将采取一个IList或IEnumerable的作为参数,所以我不能简单的新一轮上涨。有没有看起来更像选项1是我的思念,还是我只是太挑剔挑剔这里的选项2一个真正的选择是合理的选择。

ObservableCollection doesn't have a constructor that will take an IList or IEnumerable as a parameter, so I can't simple new one up. Is there an alternative that looks more like option 1 that I'm missing, or am I just being too nit-picky here and option 2 really is a reasonable option.

另外,如果选择2是唯一真正的选择,有一个理由去使用一个IList一个多IEnurerable如果所有我曾经真的打算用它做的是遍历返回值,并将其添加到一些其他类型收集的?

Also, if option 2 is the only real option, is there a reason to use an IList over an IEnurerable if all I'm ever really going to do with it is iterate over the return value and add it to some other kind of collection?

在此先感谢

推荐答案

您可以写一个快速和肮脏的扩展方法,可以很容易

You could write a quick and dirty extension method to make it easy

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable) { var col = new ObservableCollection<T>(); foreach ( var cur in enumerable ) { col.Add(cur); } return col; }

现在,你可以只写

return GetIlist().ToObservableCollection();

更多推荐

IList的&LT; T&GT;到的ObservableCollection&LT; T&GT;

本文发布于:2023-11-07 06:38:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565791.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:LT   IList   ObservableCollection   GT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!