无法隐式转换类型'System.Collections.Generic.IEnumerable

时间:2014-05-22 14:07:21

标签: c# linq

我需要使用(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;
            }
        }

1 个答案:

答案 0 :(得分:5)

所有linq查询都返回IEnumerable(或某些派生变量,如IOrderedEnumerable),因此您只需要将其转换为list

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);