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)