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 onIEnumerable<X>will still returnIEnumerable<X>just filtered to contain only elements of the typeT.listOfItems.OfType<T>()called onIEnumerable<X>will returnIEnumerable<T>containing elements that can be casted to typeT.listOfItems.Cast<T>()called onIEnumerable<X>will returnIEnumerable<T>containing elements casted to typeTor 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 –Wherefilters all elements that areTbut still leaving the typeIEnumerable<X>and thenCastagain tries to cast them toTbut this time returningIEumerable<T>.