C
C#•2y ago
big OOF

Yield return

I saw this code and got a little confused:
foreach (var entity in courses)
yield return EntityToModel.CreateCourseFromEntity(entity);
foreach (var entity in courses)
yield return EntityToModel.CreateCourseFromEntity(entity);
What is the reasoning behind yield return in this case? Im thinking a normal return would break the foreach and that there are no need for using yield. When googling i found that the yield can be useful to reduce code(look at attached image for example) but i cant see how it is contributing to that in the case mentined above. Thanks in advance 🙂
3 Replies
Scott
Scott•2y ago
yield return is used to lazily return a collection, whereas regular return would just return the first item from that collection in that above code sample (if you kept everything else in the code the same) If you wanted to return the entire collection using a regular return instead of yield return, you'd probably do something like return courses.Select(entity => EntityToModel.CreateCourseFromEntity(entity)); (which internally does basically the same thing as in your first message)
big OOF
big OOF•2y ago
Ah okey then i understand! Thank you 🙂
MODiX
MODiX•2y ago
That command had an error
UnknownCommand: Unknown command.
Remove your reaction to delete this message
Want results from more Discord servers?
Add your server
More Posts