IList的< T>到的ObservableCollection< T> [英] IList<T> to ObservableCollection<T>

查看:175
本文介绍了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;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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