IList<T>到 ObservableCollection<T> [英] IList&lt;T&gt; to ObservableCollection&lt;T&gt;

查看:18
本文介绍了IList<T>到 ObservableCollection<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Silverlight 应用程序中有一个当前返回 IList 的方法,我想找到最简洁的方法将其转换为 ObservableCollection,因此:

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 是唯一真正的选项,是否有理由在 IEnurerable 上使用 IList,如果我真正要做的就是迭代返回值并将其添加到其他类型收藏?

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

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