What is the purpose/advantage of using yield return iterators in C#?

前端 未结 10 1828
独厮守ぢ
独厮守ぢ 2020-12-04 06:43

All of the examples I\'ve seen of using yield return x; inside a C# method could be done in the same way by just returning the whole list. In those cases, is th

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 07:20

    Using the yield return you can iterate over items without ever having to build a list. If you don't need the list, but want to iterate over some set of items it can be easier to write

    foreach (var foo in GetSomeFoos()) {
        operate on foo
    }
    

    Than

    foreach (var foo in AllFoos) {
        if (some case where we do want to operate on foo) {
            operate on foo
        } else if (another case) {
            operate on foo
        }
    }
    

    You can put all of the logic for determining whether or not you want to operate on foo inside your method using yield returns and you foreach loop can be much more concise.

提交回复
热议问题