How does OfType<T>() Work?

Posted by TheCloudlessSky on Stack Overflow See other posts from Stack Overflow or by TheCloudlessSky
Published on 2010-05-14T11:23:21Z Indexed on 2010/05/14 11:24 UTC
Read the original article Hit count: 132

Filed under:
|
|

How does OfType() Work?

I read this link about what's going on but how exactly does the LINQ provider know how to get all objects matching the specified type. I know the IQueryable<T> "chains" up requests and then evaluates when GetEnumerator() is called (right?).

Specifically I want to know how does the framework quickly do type comparison? I wrote a method in a .NET 2.0 project that went like this (since 2.0 doesn't support these kind of features):

    public IEnumerable<TResult> OfType<TResult>()
        where TResult : class
    {
        foreach (TItem item in this.InnerList)
        {
            TResult matchItem = item as TResult;

            if (matchItem != null)
            {
                yield return matchItem;
            }
        }
    }

Is this the best implementation?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ