AsQueryable() chuyển đổi IEnumerable<T> thành IQueryable<T>, cho phép xây dựng cây biểu thức (expression tree) để thực thi trên nguồn dữ liệu từ xa (như SQL Server qua Entity Framework).
Ví dụ minh họa
using System;
using System.Linq;
class Demo
{
static void Main()
{
var arr = new int[] { 100, 200, 300, 400 };
int res = Queryable.Sum(arr.AsQueryable());
Console.WriteLine("Tổng: " + res);
}
}
Kết quả đầu ra
Tổng: 1000
Phân biệt:
IEnumerable<T>: LINQ to Objects - thực thi trong bộ nhớ (in-memory)IQueryable<T>: LINQ to SQL/EF - dịch thành SQL, thực thi trên DB
Lưu ý: Dùng AsQueryable() chủ yếu khi xây dựng thư viện chung cho cả in-memory và database.