Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

c# - How to make new IEnumerable collection and return it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...