在()扩展()和检查类型;> OfType℃之间的区别
除了可读性,是下面的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>();
和
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为T)
要求IEnumerable的< X>
仍然会返回的IEnumerable< X>
只是过滤,包含键入T的唯一元素
。
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>()
要求的IEnumerable< X> ;
将返回的IEnumerable< T>
可铸造键入包含元素 T
。
listOfItems.OfType<T>()
called on IEnumerable<X>
will return IEnumerable<T>
containing elements that can be casted to type T
.
listOfItems.Cast< T>()
要求的IEnumerable< X> ;
将返回的IEnumerable< T>
含铸造输入元素 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.
和 listOfItems.Where(D => ; d为T).Cast< T>()
基本上是做同样的事情两次 - 其中,
过滤所有元素都是 T
,但仍留下键入的IEnumerable< X>
然后铸造
再次尝试将其转换为 T
但这次返回 IEumerable< T>
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>
.