這些陳述做同樣的事情嗎?
var listA = someList.TakeWhile(predicate);
foreach(var item in listA)
{
/// perform code here
}
相對...
foreach(var item in someList.TakeWhile(predicate))
{
/// perform some code here
}
是先創建集合,然后迭代 O(N^2) 嗎?還是集合在創建 O(N) 時迭代?
uj5u.com熱心網友回復:
@Jeremy Lakeman 在評論中提供了正確答案。
變數的型別listA在:
var listA = someList.TakeWhile(predicate);
是IEnumerable<T>,T 是您的集合中單個元素的型別someList。方法的簽名清楚地表明了這一點TakeWhile:
public static System.Collections.Generic.IEnumerable<TSource> TakeWhile<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,int,bool> predicate);
如TakeWhile檔案頁面所示。
宣告型別的變數IEnumerable<T>不會列舉它。要列舉 an IEnumerable,您必須明確地進行操作,foreach例如通過列舉它 if 一個回圈,或者通過使用它來生成一個新的物化集合,例如 a List,Dictionary等...通過呼叫諸如.ToList()orToDictionary()等??方法...
這在(例如)ToList檔案中明確說明:
該
ToList<TSource>(IEnumerable<TSource>)方法強制立即查詢評估并回傳List<T>包含查詢結果的 a。您可以將此方法附加到查詢中,以獲取查詢結果的快取副本。ToArray具有類似的行為,但回傳一個陣列而不是一個List<T>.
因此,在您的兩個代碼示例中,IEnumerable您的構造將在foreach回圈中僅列舉一次。
另外:即使您在列舉之前已經實作了您的集合:
var listA = someList
.TakeWhile(predicate)
.ToList(); // Notice the .ToList() call that forces the enumeration.
foreach(var item in listA)
{
/// perform code here
}
它仍然是 O(n) 操作,而不是 O(n^2)。如果您從someList集合中獲取 N 個元素,您將在.ToList()呼叫中列舉它們一次,并在foreach回圈中列舉一次,總共 2 x N,而不是 N^2。
uj5u.com熱心網友回復:
兩種形式都是一樣的。根據 Microsoft 檔案,查詢 ( )在直接或通過 foreach 呼叫其方法TakeWhile之前不會執行。GetEnumerator
GetEnumerator在通過直接呼叫其方法或foreach在 Visual C# 或For EachVisual Basic 中使用列舉物件之前,不會執行此方法表示的查詢。
資源
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/489184.html
下一篇:每10行創建摘要
