Reputation: 77
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
Reputation: 223282
You can use Enumerable.OfType<T>
like:
foreach (var h in lstBoxAnimals.Items.OfType<Herbivore>())
{
veg.Add(h);
}
Upvotes: 2