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

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

Given this code:

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


        
      
      
      
8条回答
  •  一整个雨季
    2020-12-22 15:45

    With the "list" code, you have to process the full list before you can pass it on to the next step. The "yield" version passes the processed item immediately to the next step. If that "next step" contains a ".Take(10)" then the "yield" version will only process the first 10 items and forget about the rest. The "list" code would have processed everything.

    This means that you see the most difference when you need to do a lot of processing and/or have long lists of items to process.

提交回复
热议问题