0

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

using this code:

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

I get this error:

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.

  • 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;
            }
        }
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 2
    see [msdn](http://msdn.microsoft.com/ru-ru/library/cc679169(v=vs.110).aspx), you can try something like `ObservableCollection test = new ObservableCollection(allShopsForCat.Where(x => x.IsMallExternal == false))` – Grundy May 22 '14 at 14:09
  • 1
    Have you looked at [this](http://stackoverflow.com/a/14969012/290343)? – Ofer Zelig May 22 '14 at 14:10

1 Answers1

5

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

UPDATE

This work fine:

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);
sondergard
  • 3,184
  • 1
  • 16
  • 25