LINQ to SQL 預設以 IQueryable<T> 在伺服器端執行。若查詢包含無法轉譯為 SQL 的客戶端邏輯(如自訂方法),必須先將序列轉為 IEnumerable<T> 在本機執行。
var q = from p in db.Products.AsEnumerable()
where IsValidProduct(p) // 自訂方法,無法轉 SQL
select p;
說明:AsEnumerable() 使後續 Where 使用 LINQ to Objects 執行。
var q = from c in db.Customers where c.City == "London" select c;
Customer[] qArray = q.ToArray();
var q = from e in db.Employees where e.HireDate >= new DateTime(1994,1,1) select e;
List<Employee> qList = q.ToList();
var q = from p in db.Products
where p.UnitsInStock <= p.ReorderLevel && !p.Discontinued
select p;
Dictionary<int, Product> dict = q.ToDictionary(p => p.ProductID);
foreach (int key in dict.Keys) Console.WriteLine(key);
說明:以 ProductID 為鍵,整筆 Product 實體為值。