Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does OfType<T>() Work?

Tags:

c#

.net

linq

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?

EDIT: My main concern with this OfType<T>() is that it is fast.

like image 415
TheCloudlessSky Avatar asked May 14 '10 11:05

TheCloudlessSky


People also ask

What is the function Of the OfType()?

The OfType<TResult>(IEnumerable) method returns only those elements in source that can be cast to type TResult . To instead receive an exception if an element cannot be cast to type TResult , use Cast<TResult>(IEnumerable).

What is OfType C#?

The OfType is a filter operation and it filters the collection based on the ability to cast an element in a collection to a specified type. It searches elements by their type only. Syntax.


1 Answers

Your current implementation -- by design -- doesn't support value-types.

If you wanted something closer to LINQ's OfType method, that supports all types, then try this:

public IEnumerable<TResult> OfType<TResult>(IEnumerable source)
{
    foreach (object item in source)
    {
        if (item is TResult)
            yield return (TResult)item;
    }
}
like image 88
LukeH Avatar answered Nov 02 '22 22:11

LukeH