New Horizons Get Schooled Blog

Fetch items from a collection using ‘Yield’ instead of Temporary Collections (C#/.Net)

Posted on 12/27/18 10:00 AM by Get Schooled in C Plus, in .NET

A temporary list is a common solution if you want to retrieve and hold items from a collection for later use.—like a basket full of apples at the ready for when you get hungry later. Just as a basket of apples would be heavy to lug around, the temporary list can be computationally taxing. Instead of using temporary collections, try using Yield to spread the computational cost over a greater length of time. Because Yield return only requires the next item before returning, it’s much more lightweight.

For example:  public IEnumerable<int> GetValuesGreaterThan100(List<int> masterCollection) { foreach (var value in masterCollection) { if (value > 100) yield return value; }}

0 CommentsContinue Reading →

Search by Topic

    Lists by Topic

    see all

    Be at the center of it all.

    SUBSCRIBE TO NEWSLETTER

    Knowledge Ninjas

    a web-based service that allows software application end users to access a subject matter expert in real-time via a chat interface to resolve questions or problems they encounter in their specific software.