在()扩展()和检查类型;> 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):


  1. listOfItems.Where(T =&GT; t为T)要求 IEnumerable的&LT; X&GT; 仍然会返回的IEnumerable&LT; X&GT; 只是过滤,包含键入 T的唯一元素

  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.

listOfItems.OfType&LT; T&GT;()要求的IEnumerable&LT; X&GT ; 将返回的IEnumerable&LT; T&GT; 可铸造键入包含元素 T

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

listOfItems.Cast&LT; T&GT;()要求的IEnumerable&LT; X&GT ; 将返回的IEnumerable&LT; T&GT; 含铸造输入元素 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 =&GT ; d为T).Cast&LT; T&GT;()基本上是做同样的事情两次 - 其中,过滤所有元素都是 T ,但仍留下键入的IEnumerable&LT; X&GT; 然后铸造再次尝试将其转换为 T 但这次返回 IEumerable&LT; T&GT;

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>.