何时在 Linq 中使用 Cast() 和 Oftype() [英] When to use Cast() and Oftype() in Linq

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

问题描述

我知道有两种方法可以将类型从 Linq 中的 Arraylist 转换为 IEnumerable 并想知道在哪些情况下使用它们?

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 的元素.
Cast - 将尝试将所有元素转换为类型 x.如果其中一些不是来自这种类型,您将收到 InvalidCastException

OfType - return only the elements that can safely be cast to 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 中使用 Cast() 和 Oftype()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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