LINQ Cast()方法

本文概述

  • LINQ Cast()转换运算符的语法
  • LINQ Cast转换运算符的示例
在LINQ中, 使用Cast运算符将集合中存在的所有元素都转换/转换为新集合的指定数据类型。如果我们尝试在集合中强制转换/转换不同类型的元素(字符串/整数), 则转换将失败, 并且将引发异常。
LINQ Cast()转换运算符的语法 C#代码
IEnumerable< string> result = obj.Cast< string> ();

LINQ Cast转换运算符的示例
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1{class Program{static void Main(string[] args){//create an object named 'obj' of ArrayList ArrayList obj = new ArrayList(); //assign the values to the object 'obj' obj.Add("USA"); obj.Add("Australia"); obj.Add("UK"); obj.Add("India"); //Here we are converting the ArrayList object to String type of object and store the result in 'result'IEnumerable< string> result = obj.Cast< string> (); //Now with the help of foreach loop we will print the value of resultforeach (var item in result){Console.WriteLine(item); }Console.ReadLine(); }}}

【LINQ Cast()方法】输出
LINQ Cast()方法

文章图片
在上面的示例中, 我们有一个Arraylist, 在其中添加了一些国家。这些国家/地区是一种类型的对象, 通过使用Cast运算符, 我们将ArrayList对象转换为String类型的对象。

    推荐阅读