How does the OfType <T> () function work?

How does the OfType () function work?

I read this link about what is happening, but how exactly does the LINQ provider know how to get all the objects matching the specified type. I know IQueryable<T> β€œup” queries and then evaluates when GetEnumerator() is called (right?).

In particular, I want to know how the system quickly performs type comparisons? I wrote a method in a .NET 2.0 project that went like this (since 2.0 does not support such functions):

  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 a better implementation?

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

+7
c # linq
source share
2 answers

Your current implementation - by design - does not support value types.

If you need something closer to the LINQ OfType method, which supports all types, try the following:

 public IEnumerable<TResult> OfType<TResult>(IEnumerable source) { foreach (object item in source) { if (item is TResult) yield return (TResult)item; } } 
+10
source share

For me, this looks like a good implementation, but it looks like a specific implementation (you mean this.InnerList). If you created an extension method (supported in 2.0, right?) That extends IEnumerable, you can use it in any enumerated collection, right?

0
source share

All Articles