As @somebody pointed out, the right way to do this is to use yield return
:
public static IEnumerable<int> Filter(IEnumerable<int> numbers, Func<int, bool> filter) {
foreach (int number in numbers) {
if (filter.Invoke(number)) {
yield return number;
}
}
}
When your returned collection (your returned IEnumerable<int>
) is enumerated (via a foreach
or a call to something like ToList
), then you code will be called for the first item. When you get to the yield return
, the first number will be returned. When the second pass (and subsequent passes) through the iteration occurs, the code will continue to execute on the line following the yield return
.
For what it's worth, your code is pretty much exactly what LINQ's Where
extension method does for IEnumerable<T>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…