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

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

Given this code:

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


        
      
      
      
8条回答
  •  伪装坚强ぢ
    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.

提交回复
热议问题