1. 程式人生 > >LINQ實現

LINQ實現

div class csharp 方法 yield 進行 urn spa har

public static IEnumerable<TSource> MyWhere<TSource>(

this IEnumerable<TSource> source, Func<TSource, bool> predicate) { foreach (TSource item in source) { if (predicate(item)) yield return item; } }

Yield叠代器,延遲計算

1) Yield叠代器

在上面定義的MyWhere擴展方法中,我們使用了yield叠代器。使我們不必“顯示”實現IEnumerable或IEnumerator接口。只需要簡單的使用 yield 關鍵字,由 JIT 編譯器幫我們編譯成實現 IEnumerable或IEnumerator 接口的對象(即:本質還是傳統遍歷,只是寫法上非常簡潔),就能使用foreach進行遍歷。

LINQ實現