I’ve got a base class, say called Fruits. I then have a few child classes of that, say Banana:Fruit, Apple:Fruit, etc.
I then have a list of objects of different types, Banana, Apple, whatever. That looks like this:
List<Fruits> f = new List<Fruits>{new Banana(), new Banana(), new Apple(), new Banana()};
I want a function that can take a list of fruits as well as a type, and give me a list with only that type’s objects in the list. So if I call find_obj(f, Banana), (or something) it should give me back a list containing only Bananas.
I might be showing extreme ignorance here, and I apologise. Is this even possible? I know I could do something like this if I know the class beforehand:
public List<Fruit> GimmeBanana(List<Fruit> f)
{
List<Fruit> Output=new List<Fruit>{ };
foreach(Fruit fr in f)
{
if (fr is Banana){ Output.Add(fr); }
}
}
But I don’t know how to make that work for Any class.
Such a method already exists in the framework –
OfType<T>: