方案1:
var query1 = (from a in this.Context.Blah select a); // you have a query
var query2 = (from b in this.Context.Yada select b); // you have another query
var query3 = (query1.Union(query2)); // you build a new query
var result = query3.ToList(); // you execute a query and get result
方案2:
//this builds a query and execute it and get result from database
var query1 = (from a in this.Context.Blah select a).ToList(); // you execute a query
//this builds a query and execute it and get result from database
var query2 = (from b in this.Context.Yada select b).ToList(); // you execute another query
//this builds a query and execute it but it does not hit database because you are working
//with IEnumerable here not IQueryable
var query3 = (query1.Union(query2)); // you build a new query
var result = query3.ToList(); // you execute another query and get result
情景2執行3查詢,並有2個往返數據庫,而第一個就去拿你想要什麼一次往返。
構建查詢並執行它有很大的區別。調用方法如ToList
,ToArray
,First
,Single
和...將執行您建立的查詢,因爲像Where
,Union
,Except
和Except
和Except
這樣的調用方法正在爲您建立查詢。
**這是否有任何性能改善?或者它本質上是相同的東西?** 'ToList()'降低了性能,因爲它執行LINQ-to-SQL查詢(命中數據庫)。這將在實際工作之前完成2次(工會電話)。 不調用'ToList()'直到最終查詢被構造,你就是'推遲執行'(並推遲到db的往返)。 在某些操作中,處理內存中的數據結果比使數據庫在其上運行更快*。一個好的經驗法則,「只要有可能,就讓數據庫完成這項工作。」 – Alan
這是特定於LINQ到XML的,但延遲評估的概念在所有LINQ類型中都很重要:https://msdn.microsoft.com/en-us/library/bb943859.aspx – Alan