Why use the yield keyword, when I could just use an ordinary IEnumerable?

前端 未结 8 1235
渐次进展
渐次进展 2020-12-22 15:08

Given this code:

IEnumerable FilteredList()
{
    foreach( object item in FullList )
    {
        if( IsItemInPartialList( item ) )
                 


        
                      
相关标签:
8条回答
  • 2020-12-22 15:46

    Using yield makes the collection lazy.

    Let's say you just need the first five items. Your way, I have to loop through the entire list to get the first five items. With yield, I only loop through the first five items.

    0 讨论(0)
  • 2020-12-22 15:51

    why use [yield]? Apart from it being slightly less code, what's it do for me?

    Sometimes it is useful, sometimes not. If the entire set of data must be examined and returned then there is not going to be any benefit in using yield because all it did was introduce overhead.

    When yield really shines is when only a partial set is returned. I think the best example is sorting. Assume you have a list of objects containing a date and a dollar amount from this year and you would like to see the first handful (5) records of the year.

    In order to accomplish this, the list must be sorted ascending by date, and then have the first 5 taken. If this was done without yield, the entire list would have to be sorted, right up to making sure the last two dates were in order.

    However, with yield, once the first 5 items have been established the sorting stops and the results are available. This can save a large amount of time.

    0 讨论(0)
提交回复
热议问题