Francis Gall
Francis Gall

Reputation: 77

How to filter a collection of objects

I have a animal class. a herbivore class which inherits from animal and a elephant class which inherits from herbivore. I also have a carnivore class which inherits from animal and a tiger class which inherits from carnivore. I Have a observable collection called zoo with tigers and elephants. I have a listbox hooked up to the zoo collection. How do I filter for example when a button in clicked just to show tigers or eg to show elephants.I tried this eg buttonCLick event

        ObservableCollection<Animal> veg = new ObservableCollection<Animal>();

        foreach (Herbivore h in lstBoxAnimals.Items)
        {
            veg.Add(h);
        }
        lstBoxAnimals.ItemsSource = veg;

Invalid cast exception was error message is there a different way of doing this??

Upvotes: 1

Views: 70

Answers (1)

Habib
Habib

Reputation: 223282

You can use Enumerable.OfType<T> like:

foreach (var h in lstBoxAnimals.Items.OfType<Herbivore>())
{
  veg.Add(h);
}

Upvotes: 2

Related Questions