无法隐式转换类型'System.Collections.Generic.IEnumerable [英] Cannot implicitly convert type 'System.Collections.Generic.IEnumerable

查看:798
本文介绍了无法隐式转换类型'System.Collections.Generic.IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to filter a ObservableCollection with a(Where(x=>x.IsMallExternal == false)).

使用此代码:

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>'. 

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

So I am using this code as a solution instead, but seems not the best way.

  • 我想知道如何在我的方法中使用.Where过滤ObservableCollection.
  • I would like to know how to filter ObservableCollection with .Where in my method.
   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;
            }
        }

推荐答案

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

All linq queries return IEnumerable (or some derived variant such as IOrderedEnumerable), so you just need to convert it to 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);

这篇关于无法隐式转换类型'System.Collections.Generic.IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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