无涯教程-Linq cast()方法

76 阅读1分钟

在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&lt;string&gt; result = obj.Cast&lt;string&gt;();

//Now with the help of foreach loop we will print the value of result foreach (var item in result)

        {

            Console.WriteLine(item);

        }

        Console.ReadLine();

    }

}

}

输出:

LINQ Cast() Method

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






参考链接

www.learnfk.com/linq/linq-c…