当在LINQ to使用CAST()和Oftype() [英] When to use Cast() and Oftype() in Linq

查看:310
本文介绍了当在LINQ to使用CAST()和Oftype()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道铸类型的IEnumerable 的ArrayList Linq中,不知道在何种情况下的两种方法使用它们?

I am aware of two methods of casting types to IEnumerable from an Arraylist in Linq and wondering in which cases to use them?

例如

IEnumerable<string> someCollection = arrayList.OfType<string>()

IEnumerable<string> someCollection = arrayList.Cast<string>()

这两种方法,我应该在哪里申请每种情况?

What is the difference between these two methods and where should I apply each case?

推荐答案

OfType - 返回式x的唯一的要素
铸造 - 将尝试转换所有的元素融入到X型。如果他们中的一些是不是这种类型,你将获得 InvalidCastException的

OfType - return only the elements of type x.
Cast - will try to cast all the elements into type x. if some of them are not from this type you will get InvalidCastException

修改
例如:

object[] objs = new object[] { "12345", 12 };
objs.Cast<string>().ToArray(); //throws InvalidCastException
objs.OfType<string>().ToArray(); //return { "12345" }

这篇关于当在LINQ to使用CAST()和Oftype()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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