FirstOrDefault on collection of objects
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.
精彩评论