Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FirstOrDefault on collection of objects

Tags:

c#

linq

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?

like image 387
Ben Williams Avatar asked Dec 09 '22 14:12

Ben Williams


2 Answers

var firstCow = animals.OfType<Cow>().FirstOrDefault();
like image 159
Bryan Watts Avatar answered Dec 26 '22 03:12

Bryan Watts


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.

like image 37
Metro Smurf Avatar answered Dec 26 '22 02:12

Metro Smurf