I have something like the following classes:
public class Animal
{
...
}
public class Cow : Animal
{
...
}
public class AnimalCollection : List<Animal>
{
public Animal GetFirstAnimal<T>()
{
foreach(Animal animal in this)
{
if(animal is T)
return T as Animal
}
return null;
}
}
A few questions: Is it possible to use FirstOrDefault on the collection instead of having the GetFirstAnimal() method? What would be the syntax if you can? Also which would be the most efficient? It isn't going to be a massive collection.
Alternatively, is there a better way of doing the same thing all together?
var firstCow = animals.OfType<Cow>().FirstOrDefault();
An alternative to using OfType
which actually iterates the entire list, you could use the overload of FirstOrDefault
and pass in a predicate:
var firstAnimal = animals.FirstOrDefault( x => x is Animal ) as Animal;
Edit: as correctly noted by @Lee in the comments, OfType
does not iterate the entire list; rather OfType
will only iterate the collection until the FirstOrDefault
predicate is matched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With