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
Let us compare three methods (pay attention to generic arguments):
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
.
listOfItems.OfType<T>()
called on IEnumerable<X>
will return IEnumerable<T>
containing elements that can be casted to type T
.
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>
.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With