【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.IEnumerable [duplicate]无法隐式转换类型'System.Collections.Generic.IEnumerable [重复]
【发布时间】:2014-05-22 14:07:21
【问题描述】:

我需要使用(Where(x=>x.IsMallExternal == false)) 过滤 ObservableCollection。

使用此代码:

ObservableCollection<Shop> test = allShopsForCat.Where(x => x.IsMallExternal == false);

我收到此错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<DataModel.Shop>' to 'System.Collections.ObjectModel.ObservableCollection<DataModel.Shop>'. 

所以我改用这段代码作为解决方案,但似乎不是最好的方法。

  • 我想知道如何在我的方法中使用.Where 过滤 ObservableCollection。

   public ObservableCollection<Shop> Shops
        {
            get
            {
                ObservableCollection<Shop> allShopsForCat = App._dataSource.GetShopsForCategoryAll(_id);

                //ObservableCollection<Shop> test = allShopsForCat.Where(x => x.IsMallExternal == false); // THIS DOES NOT WORK
                ObservableCollection<Shop> shopsNotExternal = new ObservableCollection<Shop>();
                // Get only shops for category which are internal to mall
                foreach (var shop in allShopsForCat)
                {
                    if (shop.IsMallExternal == false)
                    {
                        shopsNotExternal.Add(shop);
                    }
                }
                return shopsNotExternal;
            }
        }

【问题讨论】:

  • msdn,你可以试试ObservableCollection&lt;Shop&gt; test = new ObservableCollection&lt;Shop&gt;(allShopsForCat.Where(x =&gt; x.IsMallExternal == false))
  • 你看过this吗?

标签: c# linq


【解决方案1】:

所有 linq 查询都返回 IEnumerable(或一些派生的变体,例如 IOrderedEnumerable),因此您只需将其转换为列表

var filtered = allShopsForCat.Where(x => x.IsMallExternal == false);
ObservableCollection<Shop> shopsNotExternal = new ObservableCollection<Shop>(filtered);

更新

这项工作很好:

List<int> temp = new List<int> { 1, 3, 5, 5, 6, 7, 7, 8 };

var filtered = temp.Where(i => i == 5 || i == 7);
ObservableCollection<int> l = new ObservableCollection<int>(filtered);

【讨论】:

  • 请您仔细检查一下...它抛出了同样的异常。
  • 我添加了一个带有简单整数列表的示例,它按预期工作。
  • 感谢您的评论
  • 我已经用你的样本制作了一个小提琴,再次感谢dotnetfiddle.net/TAj6YS
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-24
  • 1970-01-01
相关资源
最近更新 更多