FirstOrDefault for collecting 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 for a collection instead of the GetFirstAnimal () method? What would be the syntax, if possible? And what will be the most effective? This will not be a massive collection.

Alternatively, is there a better way to do the same all together?

+3
source share
2 answers
var firstCow = animals.OfType<Cow>().FirstOrDefault();
+11
source

An alternative to using OfType that actually iterates the entire list , you can use overloading FirstOrDefaultand pass the predicate:

var firstAnimal = animals.FirstOrDefault( x => x is Animal ) as Animal;

: @Lee, OfType ; OfType , FirstOrDefault .

+2

Source: https://habr.com/ru/post/1756473/


All Articles