Linq cast()方法

Linq cast()方法 首页 / LinQ入门教程 / 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 result
            foreach (var item in result)

            {

                Console.WriteLine(item);

            }

            Console.ReadLine();

        }

    }
}

输出:

LINQ Cast() Method

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






祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

玩转Git三剑客 -〔苏玲〕

iOS开发高手课 -〔戴铭〕

从0打造音视频直播系统 -〔李超〕

性能工程高手课 -〔庄振运〕

Django快速开发实战 -〔吕召刚〕

技术领导力实战笔记 2022 -〔TGO 鲲鹏会〕

B端产品经理入门课 -〔董小圣〕

结构思考力 · 透过结构看问题解决 -〔李忠秋〕

AI 应用实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)