12/04/2009

Filter a list of child objects from a list of parent objects

You have a list of generic parent objects consisting of various child objects. You want to filter out a list of a objects consisting of one of the child classes. Here's the code:

class ChildObjectListFilterer<Tparent, Tchild>
{
    IList<Tparent> parentObjectList;

    public ChildObjectListFilterer(IList<Tparent> parentObjectList)
    {
        this.parentObjectList = parentObjectList;
    }

    public IList<Tchild> getChildObjects()
    {
        IList<Tchild> returnVal = new List<Tchild>();

        foreach (object o in parentObjectList)
        {
            if (o.GetType() == typeof(Tchild))
            {
                returnVal.Add((Tchild)o);
            }
        }

        return returnVal;
    }
}

0 comments:

Post a Comment