Linq 延遲執行

2021-07-04 22:28:48 字數 2426 閱讀 8302

使用linq時,其中乙個重要概念就是延遲執行,所有的謂詞求值需要等到觸發時才會被呼叫。在宣告時,它們是不執行的,除非呼叫lambda表示式,造成其中的**開始執行,否則不會被執行。如果lambda表示式執行的代價比較高(如呼叫資料庫,密集計算等),那麼為了優化**,通過使用」to***」方法來轉換為集合方式,減少lambda表示式的執行。但轉換後會造成整個結果都載入到記憶體(在此之前可能駐留在乙個資料庫或檔案中)。除此之外,」to***」方法會建立基礎資料的」快照」,需保證在查詢」to***」方法的結果時,不會返回新的結果。測試**如下:

public class patent 

public string yearofpublication

public long inventorids

public override string tostring()

()",title,yearofpublication);}};

public class inventor

public string name

public string city

public string state

public string country

public override string tostring()

(,)",name,city,state);}};

public static class patentdata

,new inventor() ,

new inventor() ,

new inventor()

};public static readonly patent patents = new patent

},new patent()

},new patent()

},new patent()

},new patent()

},new patent()

},new patent()

},new patent()

},};

};class program

}static void main(string args)

return result;});

console.writeline("1. patents prior to the 1900s are:");

foreach (patent patent in patents)

console.writeline();

console.writeline("2. a second listing of patents prior to the 1900s:");

console.writeline(" there are patents prior to 1900.",patents.count());

console.writeline();

console.writeline("3. a third listing of patents prior to the 1900s:");

patents = patents.toarray();

console.write(" there are ");

console.writeline(" patents prior to 1900.",patents.count());

console.readline();

}}

執行結果如下:

1. patents prior to the 1900s are:

phonograph(1877)

hello in patent.

kinetoscope(1888)

hello in patent.

electrical telegraph(1837)

hello in patent.

steam locomotive(1815)

hello in patent.

2. a second listing of patents prior to the 1900s:

phonograph(1877)

kinetoscope(1888)

electrical telegraph(1837)

steam locomotive(1815)

there are 4 patents prior to 1900.

3. a third listing of patents prior to the 1900s:

phonograph(1877)

kinetoscope(1888)

electrical telegraph(1837)

steam locomotive(1815)

there are 4 patents prior to 1900.

具體**分析詳見<

Linq基礎知識之延遲執行

linq中的絕大多數查詢運算子都有延遲執行的特性,查詢並不是在查詢建立的時候執行,而是在遍歷的時候執行,也就是在enumerator的movenext 方法被呼叫的時候執行,大說數linq查詢操作例項方法返回的都是ienumerable,所以只有在使用foreach遍歷的時候,查詢方法才能被真正的執...

LINQ延遲查詢

11.1.4 推遲查詢的執行 在執行期間定義查詢表示式時,查詢就不會執行,查詢會在迭代資料項時執行。比如說擴充套件方法where 它使用yield return語句返回謂詞為true的元素。因為使用了yield return語句,所以編譯器會建立乙個列舉器,在訪問列舉中的項後,就返回它們。publi...

延遲查詢 LINQ

1.linq查詢使用的是延遲查詢的方法,以便提高效率 1 public static ienumerablewhere this ienumerablesource,2 funcbool predicate 310 11 因為使用yield return,所以編譯器會建立乙個列舉器,在訪問列舉項後,...