Ngôn ngữ LINQ - Toán tử Cast

Phương thức Cast trong LINQ

Phương thức Cast thực hiện điều tương tự như phương thức AsEnumerable<T>. Nó ép kiểu một đối tượng nguồn thành kiểu IEnumerabl<T>.

class Program
{
    static void ReportTypeProperties<T>(T obj)
    {
        Console.WriteLine("Compile-time type: {0}", typeof(T).Name);
        Console.WriteLine("Actual type: {0}", obj.GetType().Name);
    }

    static void Main(string[] args)
    {
        Student[] studentArray = 
        { 
            new Student() { StudentID = 1, StudentName = "John", Age = 18 },
            new Student() { StudentID = 2, StudentName = "Steve", Age = 21 },
            new Student() { StudentID = 3, StudentName = "Bill", Age = 25 },
            new Student() { StudentID = 4, StudentName = "Ram", Age = 20 },
            new Student() { StudentID = 5, StudentName = "Ron", Age = 31 }
        };   
            
        ReportTypeProperties(studentArray);
        ReportTypeProperties(studentArray.Cast<Student>());   
    }
}

Đây là kết quả khi biên dịch và thực thi chương trình:

Compile-time type: Student[]
Actual type: Student[]
Compile-time type: IEnumerable`1
Actual type: Student[]

Xem ví dụ

studentArray.Cast<Student>() giống như (IEnumerable<Student>)studentArray. Nhưng Cast<Student>() ngắn gọn và dễ đọc hơn.

Lưu ý: Phương thức Cast không hỗ trợ cú pháp truy vấn LINQ.