yield return
i can't understand the benefits of yield return , if it's benefit to avoid fetching all data from database and storing them in the memory,and reading each data on demand.
i think i can does that by stream types,so what the need to yield return?
15 Replies
yield return is for producing sequences one element at a time, that's it
it has nothing to do with databases
and has nothing to do with reading file?
Note that Stream just works with bytes
no, it is a standalone language feature
you can use it with anything
Streams are specifically for reading sets of bytes, from a source which might be able to read 0, 1, or many bytes at that point in time
Iterators are a different mechanism. They work with any element type, and they just yield a single element at a time
some examples
i like the example, but i'm talking about real example
producing infinite sequences is a real example
i mean how c# used in in it's built-in language, what's the apply of it in the language
foreach
loops for one: the ability to iterate over collectionsAll of Linq: the ability to filter and transform sequences of elements
Also notable is that the result of an
IEnumerable<T>
function isn't called on it's assignment, but it's usage.
Combined with a filter like Where(<predicate>)
you don't need to loop over each element.
And depending on the condition, not even once.
Example:
It's mostly performance related, also by using an interface
the user is free to whatever collection one wanna implement.
A win-win situation.