在()扩展()和检查类型;> OfType℃之间的区别 [英] Difference between OfType<>() and checking type in Where() extension

查看:94
本文介绍了在()扩展()和检查类型;> 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 => t为T)要求 IEnumerable的< X> 仍然会返回的IEnumerable< X> 只是过滤,包含键入 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< 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>.

这篇关于在()扩展()和检查类型;&GT; OfType℃之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆