Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between OfType<>() and checking type in Where() extension

Tags:

c#

linq

Other than readability, what is the difference between the following linq queries and when and why would I use one over the other:

IEnumerable<T> items = listOfItems.Where(d => d is T).Cast<T>();

and

IEnumerable<T> items = listOfItems.OfType<T>();

Update: Dang, sorry introduced some bugs when trying to simplify my problem

like image 691
ajbeaven Avatar asked Jan 25 '12 23:01

ajbeaven


2 Answers

Let us compare three methods (pay attention to generic arguments):

  1. listOfItems.Where(t => t is T) called on IEnumerable<X> will still return IEnumerable<X> just filtered to contain only elements of the type T.

  2. listOfItems.OfType<T>() called on IEnumerable<X> will return IEnumerable<T> containing elements that can be casted to type T.

  3. listOfItems.Cast<T>() called on IEnumerable<X> will return IEnumerable<T> containing elements casted to type T or throw an exception if any of the elements cannot be converted.

And listOfItems.Where(d => d is T).Cast<T>() is basically doing the same thing twice - Where filters all elements that are T but still leaving the type IEnumerable<X> and then Cast again tries to cast them to T but this time returning IEumerable<T>.

like image 86
Krizz Avatar answered Sep 19 '22 02:09

Krizz


listOfItems.Where(d => d is T) returns an IEnumerable<U> (where U is the type of the items in listOfItems), containing only items of type T.

listOfItems.OfType<T>() returns an IEnumerable<T>.

like image 25
Thomas Levesque Avatar answered Sep 17 '22 02:09

Thomas Levesque