當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


LINQ Cast()用法及代碼示例

在 LINQ 中,Cast 運算符用於將集合中存在的所有元素強製轉換/轉換為新集合的指定數據類型。如果我們嘗試轉換/轉換集合中不同類型的元素(字符串/整數),則轉換將失敗,並拋出異常。

LINQ Cast() 轉換運算符的語法

C# 代碼

IEnumerable<string> result = obj.Cast<string>();

LINQ 強製轉換運算符示例

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,我們在其中添加了幾個國家。這些國家是一個Object類型,通過Cast操作符,我們將ArrayList Object轉換為String類型的對象。





相關用法


注:本文由純淨天空篩選整理自 LINQ Cast() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。