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

前端 未结 10 1846
独厮守ぢ
独厮守ぢ 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:30

    Sometimes the sequences you need to return are just too large to fit in the memory. For example, about 3 months ago I took part in a project for data migration between MS SLQ databases. Data was exported in XML format. Yield return turned out to be quite useful with XmlReader. It made programming quite easier. For example, suppose a file had 1000 Customer elements - if you just read this file into memory, this will require to store all of them in memory at the same time, even if they are handled sequentially. So, you can use iterators in order to traverse the collection one by one. In that case you have to spend just memory for one element.

    As it turned out, using XmlReader for our project was the only way to make the application work - it worked for a long time, but at least it did not hang the entire system and did not raise OutOfMemoryException. Of course, you can work with XmlReader without yield iterators. But iterators made my life much easier (I would not write the code for import so quickly and without troubles). Watch this page in order to see, how yield iterators are used for solving real problems (not just scientific with infinite sequences).

提交回复
热议问题