tags:

views:

79

answers:

2

I am absolute n00b at LINQ.

Can code for GetAnimals() be written in LINQ?

class Farm
{
    ObservableCollection<Animal> allAnimals = new ObservableCollection<Animal>();

    public IEnumerable<T> GetAnimals<T>() where T: Animal
    {
        foreach (var a in allAnimals)
        {
            if (a.GetType() == typeof(T))
            {
                yield return (T)a;
            }
        }
    }
}
+4  A: 

There's already an extension method for this: OfType

bruno conde
+10  A: 

You want Enumerable.OfType:

public IEnumerable<T> GetAnimals<T>() where T: Animal
{
    return allAnimals.OfType<T>();
}
ICR
Beat me to it - although it does seem a little much to push it out to a new method
Chris
+1 - Best solution to this kind of problem :)
cwap
@Chris True. Edited.
ICR
@Chris, the new method would give it the extra constraint where T : Animal. It might be a good idea.
bruno conde
I remember why I made it a method now - allAnimals is private, this is an accessor method.
ICR