Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Cast ใน C# LINQ


ภาพรวม

เมธอด Cast<T>() ใน LINQ ใช้ แปลง (cast) องค์ประกอบในลำดับให้เป็นชนิดที่ระบุ T เหมาะสำหรับแปลงจาก IEnumerable (non-generic) หรือ List<object> เป็นลำดับเจเนอริก

รูปแบบการใช้งาน

List list = new List { "Mac", "Windows", "Linux" };
IEnumerable strings = list.Cast();

ตัวอย่างโค้ดเต็ม: ดึง 2 ตัวอักษรแรก

using System;
using System.Linq;
using System.Collections.Generic;

class Demo
{
    static void Main()
    {
        List list = new List { "keyboard", "mouse", "joystick", "monitor" };
        // แปลงเป็น string แล้วดึง 2 ตัวอักษรแรก
        IEnumerable res = list.AsQueryable().Cast().Select(str => str.Substring(0, 2));
        foreach (string str in res) Console.WriteLine(str);
    }
}

ผลลัพธ์

ke
mo
jo
mo

ข้อสังเกตสำคัญ

  • โยน InvalidCastException หากองค์ประกอบแปลงไม่ได้ (เช่น object ที่เป็น int แปลงเป็น string)
  • ต่างจาก OfType<T>() ที่จะ กรองเฉพาะ องค์ประกอบที่เป็นชนิด T (ไม่โยน Exception)
  • ใช้กับ non-generic collections เช่น ArrayList, Hashtable.Values