I tend to use yield-return when I calculate the next item in the list (or even the next group of items).
(当我计算列表中的下一个项目(甚至是下一组项目)时,我倾向于使用yield-return。)
Using your Version 2, you must have the complete list before returning.
(使用版本2,您必须在返回之前拥有完整列表。)
By using yield-return, you really only need to have the next item before returning. (通过使用yield-return,您实际上只需要在返回之前拥有下一个项目。)
Among other things, this helps spread the computational cost of complex calculations over a larger time-frame.
(除此之外,这有助于在更大的时间范围内分散复杂计算的计算成本。)
For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list. (例如,如果列表连接到GUI并且用户永远不会转到最后一页,则永远不会计算列表中的最终项目。)
Another case where yield-return is preferable is if the IEnumerable represents an infinite set.
(另一种情况,其中yield-return是优选的,如果IEnumerable表示无限集。)
Consider the list of Prime Numbers, or an infinite list of random numbers. (考虑素数列表,或无限的随机数列表。)
You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally. (您永远不能一次返回完整的IEnumerable,因此您使用yield-return以递增方式返回列表。)
In your particular example, you have the full list of products, so I'd use Version 2.
(在您的特定示例中,您有完整的产品列表,因此我将使用版本2。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…