C# yield
Keyword: Optimizing Collection Iteration
The C# yield
keyword, introduced in C# 2.0, offers a powerful mechanism for creating efficient iterators over collections. This is particularly relevant when dealing with large datasets or scenarios where exposing only a portion of a collection is necessary.
Functionality of yield
yield
enables methods to return an IEnumerable
object. This interface represents a sequence of elements that can be iterated over using a foreach
loop. Crucially, yield
doesn't require the entire collection to be loaded into memory at once.
Instead, when a foreach
loop iterates over a yield
-based method, the method executes only until it encounters a yield return
statement. It then returns the yielded value and suspends its execution. The method resumes execution only when the next element is requested in the iteration. This is essentially a state machine that generates values on demand.
Illustrative Example
Consider a method filtering elements from a larger list:
<code class="language-csharp">IEnumerable<object> FilteredList(IList<object> fullList, IList<object> partialList) { foreach (object item in fullList) { if (partialList.Contains(item)) yield return item; } }</code>
Here, FilteredList
returns only the elements present in both fullList
and partialList
. It processes fullList
one element at a time, yielding only those that meet the condition. This avoids creating a new, potentially large, filtered list in memory.
Practical Applications
The yield
keyword finds extensive use in:
Custom Iterators: Creating iterators for custom data structures or algorithms without the overhead of pre-populating a collection.
Efficient Data Retrieval: Retrieving data from databases or other external sources incrementally, reducing memory consumption and improving performance. Consider this example of reading from a database:
<code class="language-csharp">public IEnumerable<T> ReadData<T>(string query, Func<IDataReader, T> mapper) { using (var reader = ExecuteQuery(query)) { while (reader.Read()) { yield return mapper(reader); } } }</code>
This approach fetches and processes database rows one at a time, significantly more efficient than loading the entire result set into memory.
By leveraging the yield
keyword, developers can create elegant and efficient solutions for iterating over collections, particularly when dealing with large or dynamically generated data.
The above is the detailed content of How Does the C# `yield` Keyword Enable Efficient Iteration Over Collections?. For more information, please follow other related articles on the PHP Chinese website!