Advertisement
Advanced C#, Iterators & yield return

How would you implement a custom lazy 'Where' and 'Select' from scratch using yield return, mirroring how LINQ actually works internally?

Short answer

Write generic iterator methods that take a source IEnumerable and a predicate/selector delegate, iterating the source lazily and yielding transformed/filtered results one at a time — this is conceptually exactly how System.Linq.Enumerable.Where() and .Select() are implemented…

Save C# mock interview
Advertisement
AModel answer
Write generic iterator methods that take a source IEnumerable<T> and a predicate/selector delegate, iterating the source lazily and yielding transformed/filtered results one at a time — this is conceptually exactly how System.Linq.Enumerable.Where() and .Select() are implemented, composing cleanly without ever materializing an intermediate collection.
public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
  foreach (var item in source) {
    if (predicate(item)) yield return item;
  }
}
public static IEnumerable<TResult> MySelect<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector) {
  foreach (var item in source) yield return selector(item);
}
Real-world example
Understanding LINQ's actual internal implementation strategy by reimplementing a simplified version of Where/Select yourself.
Likely follow-ups
  • Why does chaining MyWhere().MySelect() still remain fully lazy, never materializing an intermediate collection between the two calls?
Related topics