[英]which of the following linq queries will be executed
我如何知道將執行以下哪個linq查詢?
// I think this will not be executed
var temp1 = PdvEntities.Entities.Products;
// Not sure
IEnumerable<Data.Products> temp2 = PdvEntities.Entities.Products;
// will not be executed
var temp3 = from a in PdvEntities.Entities.Products select a;
ListView lv1 = new ListView();
lv1.DataContext = temp1; // will this make the first query to be executed?
lv1.ItemsSource = temp2; // will this make the second query execute?
// I think this will be executed
var temp4 = PdvEntities.Entities.Products.ToList();
注意我使用ADO.Net實體數據模型來執行我的數據庫中的表Products中的查詢
該概念稱為“延遲執行”,一般的經驗法則是,在您實際訪問基礎數據之前,不會執行查詢。 考慮它的另一種方法是,當你不再返回IEnumerable
或IQueryable
,你可能正在執行代碼,就像你最后一個temp4放入List<T>
肯定是在訪問數據。
這是一個不錯的解釋:
當UI更新列表視圖時,將評估temp2
。
除非您綁定到ListView的DataContext,否則永遠不會評估temp1
。
對於DataContext,它實際上取決於你用它做什么。 如果您從不枚舉集合,則永遠不會執行查詢。 對於ItemsSource,我相信它會在您分配它時枚舉它,以便在列表視圖中創建必要的對象,只要它向用戶顯示即可。 如果沒有顯示,我認為不會執行查詢。 簡單的方法是模擬一些真正快速的東西,這些東西可以放在代碼示例中,然后在Visual Studio中逐步完成。 這樣,您可以在之后檢查您的本地窗口以查看該集合是否已填寫。
只有最后一個,因為我沒有看到你將ListView添加到UI。
DataContext只是一個對象類型,因此它只是獲取對IEnumerable的引用。 ItemsSourceProperty 是一個IEnumrable,因此一個引用您的IEnumerable。 您將看到IEnumerable(實現)的結果的唯一方法是訪問數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.