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

Phương thức AsEnumerable trong LINQ

Phương thức AsEnumerable ép kiểu một đối tượng nguồn thành kiểu IEnumerable<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.AsEnumerable());
    }
}

Đâ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ụ

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