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

前端 未结 8 1255
渐次进展
渐次进展 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.

提交回复
热议问题